Can I add style to part of text from an <input> value or a <span>?
I have some data like:
{text text} an other text...
And I will apply style for the text between {}.
My data is: <span>{RFS.KIS.ZWO} JJD000090085077412015021014193191</span>
I don't really see the js part here.
If I understood correctly you want CSS styles on a part of text. To do this you can put that text in an html tag and add a CSS class with the desired style to it. (changed formatting)
e.g.
HTML
<span class="myStyle">text text </span> more text.
CSS
.myStyle {
color: red;
}
For SPAN:
$(function() {
var text = $("span").text();
var replaced = text.replace(/\{(.*)\}/, function( $0, $1 ) {
return "{<span style='color: red;'>".concat($1, "</span>}");
});
$("span").html(replaced);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Text: {something}</span>
Wrap your text into tags instead of "{" "}"
calsses:
<span class="mytag">text text</span> text text
not you can style your class seperatly
<style>
.mytag {
color: blue;
}
</style>
or tags for example (not working for all browsers):
<mytag>text text</mytag> text text
not you can style your tag seperatly
<style>
mytag {
color: blue;
}
</style>
Related
I have an input field where I would like to have the characters turn red after the 10th symbol.
So far I have:
var street_1 = document.getElementById('street_1');
street_1.style.color = "red";
Which changes the color of all the characters. Then I tried using:
street_1.value.substring(10,100).style.color = "red";
which of course didn't work since .style as I learned only works for the entire field and not just the value.
Since im completely new to JS I really have no idea how to approach this.
You can hide the input field, and add another span element that displays its value as follows:
HTML:
<div>
<input type="text">
<span class="text"></span>
</div>
CSS:
input {
opacity: 0;
width: 100%;
}
div {
position: relative;
border: 1px solid #000;
}
.text {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
}
.red {
color: red;
}
JS:
var span = document.querySelector('span');
var input = document.querySelector('input');
input.addEventListener('keydown', function(evt) {
var value = evt.target.value;
span.innerHTML = value.substring(0, 10) + '<span class="red">' + value.substring(10) + '</span>'
});
You can find a working fiddle here https://jsfiddle.net/v127c14p/
in html you can't define sub elements in the value of input fields because it is allways a simple string and not a html element. so you only can define the color for the input element and the complete text.
<input type="text" value="my <em style='color: red;'>test</em>"> is not possible
<input type="text" value="my test" style="color: red;"> is the only way to mark the text
what can be a sollution, define a simple div tag, write the value of your input filed inside that, and mark the text in that div tag by surrounding with a span tag and setting a class to this
Edit:
best practice is, simply show a red border on the input field and tell the user with a popup what exactly is wrong with his input (bootstrap modals or jquery-confirm.js for excample)
Note: If I explicitly need an <input> field and not just user-editable text, this solution won't work!
It is a quite old question, but maybe someone finds this solution helpful.
It uses the contenteditable tag, to allow the user to type / change text in an normal HTML element and JS to check and color the text.
The field check can, for example, also be done with "onkeyup" for immediate feedback to the user, but this will also reset the text cursor to the beginning of the field.
HTML:
<a id="sample_id" onblur="color_overlength_func('sample_id', 20)" contenteditable="true">Some Text</a>
JS:
function color_overlength_func(textfield_id, max_length) {
let text_temp = document.getElementById(textfield_id).innerHTML;
if (text_temp.length >= max_length) {
let text_OK = text_temp.substr(0, max_length);
let text_to_long = text_temp.substr(max_length);
document.getElementById(textfield_id).innerHTML = "" + text_OK + "<em style='color:red;'>" + text_to_long + "</em>";
}
}
You can find a working fiddle here: https://jsfiddle.net/kyh9803c/
You can do a substring and append a element like span and then target the span with css or js directly.
You can use CSS. Although javascript library need to load everytime
you mean something like this
<div>
HELL<span class="red" style="color:red">O</span>
</div>
Is it possible to use "::-webkit-input-placeholder" with jQuery to set a color for the placeholder text?
Something like this:
$("input::-webkit-input-placeholder").css({"color" : "#b2cde0"});
You can't really modify pseudo-selectors with JavaScript. You'll have to modify an existing a <style> element.
If possible, make a class:
.your-class::-webkit-input-placeholder {
color: #b2cde0
}
And add it to the element:
$('input').addClass('your-class');
If you don't have a stylesheet, and want to inject CSS dynamically you can use the following:
$('body').append('<style>.my_class::placeholder{color:red}</style>')
Just use my_class and the color for the placeholder.
It's handy to have a general purpose function:
function change_placeholder_color(target_class, color_choice) {
$("body").append("<style>" + target_class + "::placeholder{color:" + color_choice + "}</style>")
}
Usage:
change_placeholder_color('.my_input', 'red')
Just add this. It will inherit the color in input[type=text]:focus new color
.your-class ::placeholder{ color: inherit;}
Here is an example of dynamically setting pseudo-element styles using jQuery – it's a matter of creating a <style> element, setting its text content to the desired style declarations, and appending it to the document.
Here is a simple single-page example:
<!doctype html>
<html>
<head>
<title>Dynamic Pseudo-element Styles</title>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
$(document).ready(function() {
createStyles();
$('#slider-font-size').on('change', createStyles);
function createStyles() {
// remove previous styles
$('#ph-styles').remove();
// create a new <style> element, set its ID
var $style = $('<style>').attr('id', 'ph-styles');
// get the value of the font-size control
var fontSize = parseInt($('#slider-font-size').val(), 10);
// create the style string: it's the text node
// of our <style> element
$style.text(
'::placeholder { ' +
'font-family: "Times New Roman", serif;' +
'font-size: ' + fontSize + 'px;' +
'}');
// append it to the <head> of our document
$style.appendTo('head');
}
});
</script>
</head>
<body>
<form>
<!-- uses the ::placeholder pseudo-element style in modern Chrome/Firefox -->
<input type="text" placeholder="Placeholder text..."><br>
<!-- add a bit of dynamism: set the placeholder font size -->
<input id="slider-font-size" type="range" min="10" max="24">
</form>
</body>
</html>
I was using MaterializeCSS; I used Jquery to update CSS for input fields like this
$(".input-field").css("color", themeColor);
$(".input-field>.material-icons").css("color", themeColor);
$(".input-field>label").css("color", themeColor);
See Result:
https://codepen.io/hiteshsahu/pen/EXoPRq?editors=1000
Lets say that I have a div with a background color of #333333, and I have an input field where the user can input their own hex value, ex: #000000, and then I want the div's background color to change to #000000 on the fly....
example:
HTML:
<div class="mydiv"></div>
css:
<style type="text/css">.mydiv { background-color:#333333; }</style>
Then when the user changes the value via an input type="text" field, when the CSS should change in the style="text/css" block.
How do I make that binding?
I can't use the in my style block, because that is not valid CSS, and I don't want to do it on my like and then insert the style here... So again, I want to change the CSS in my style block, and not add a style to my div element.
Sort of like this where they update it on the fly; http://css3gen.com/box-shadow/
When you change something, the CSS behind changes, so that you can preview your element on the fly.
Use style binding
<div data-bind='style: { "backgroundColor": CustomBGC }'>
http://jsfiddle.net/nyothecat/jKysB/3/
Edit:
Since you want to update the style, you can make use of the cascading style sheet.
Define a class with init color, then create a style tag with a text binnding. Fill this one with your new color.
In your css file:
.myClass { background-color: #f00 }
Make sure to put your css file before the following
<div id="koRoot">
<div class="myClass">
<input type='text' data-bind="value: customColor" />
</div>
<style data-bind="text: myObservableStyle(customColor)"></style>
</div>
And the javascript:
$(document).ready(function () {
var ViewModel = {
customColor: ko.observable("#f00"),
myObservableStyle: function (obs) {
return ".myClass { background-color: " + obs() + " }";
}
}
ko.applyBindings(ViewModel, document.getElementById("koRoot"));
});
http://jsfiddle.net/k97ZZ/1/
pseudohtml :
<input type="text" data-bind="value:userInput">
pseudoscript:
var MyModel=function(data){
var self=this;
self.userInput=ko.observable('#333333');
self.computedCss=ko.computed(function(){
//appends Style block to head everytime userInput changes
appendal="<style>.myClass { background-color: "+self.userInput()+";!important}</style>";
$('head').append(appendal);
}
}
myModel = new MyModel({});
ko.applyBindings(myModel);
You can use the style binding along with the value binding
<input data-bind="value: inputColor" />
<div data-bind="style: { color: inputColor()}">
Something
</div>
var viewModel = {
inputColor: ko.observable()
};
Edit
Since you want to change the style element itself use the text binding on style tag. One thing to remember that entire style will be changed so you will have to maintain valid css rules before updating the element.
<style data-bind="text:inputColor"></style>
You might want to subscribe to the inputColor observable so you can change the input to valid css before populating the style element.
This question might be relevant.
You can use virtual if binding
<style type="text/css">
<!-- ko if: someExpression -->
.mydiv { background-color:#333333; }
<!-- /ko -->
<!-- ko if: !someExpression -->
.mydiv { background-color:#000000; }
<!-- /ko -->
</style>
I need to write a function that will search all the content in my HTML page for a specific string, and if it finds it then change the color of the text.
Is this possible?
Thanks
You could do that :
CSS :
.someclass {
color: red;
}
Javascript :
$('p:contains('+yourstring+')', document.body).each(function(){
$(this).html($(this).html().replace(
new RegExp(yourstring, 'g'), '<span class=someclass>'+yourstring+'</span>'
));
});
Note that this would make problems if yourstring is in a tag or an attribute.
Demonstration
Be careful to run this code before you attach handlers to your paragraphs (or the elements inside which could contain yourstring, for example links).
The problem with dystroy's answer is that it will overwrite the entire HTML, so if you have any handlers within a node containing your text, they will be removed.
The correct solution is to use text ranges to update only the text itself, not all of the HTML around it. See Highlight text range using JavaScript
And for fun, there is a built-in method window.find that works in FF and Chrome. It's not in the standard though and will only find one at a time. Just like ctrl+f.
window.find("anything");
JQuery Find and change style of a string >> Only Copy Paste and run :)
$('#seabutton').click(function()
{
var sea=$('#search').val();
var cont=$('p').val();
alert(cont);
$('p:contains('+sea+')').each(function()
{
/* $(this).html($(this).html().replace(new RegExp(sea, 'g'),'<span class=someclass>'+sea+'</span>'));
*/ $(this).html($(this).html().replace(
new RegExp(sea, 'i'), '<span class=someclass>'+sea+'</span>'
));
});
});
$('p').click(function()
{
$(".someclass").css("color", "black");
});
$('#search').blur(function()
{
$(".someclass").css("color", "black");
});
})
</script>
<style type="text/css">
.someclass {
color: red;
}
</style>
</head>
<body>
<!-- Select Country:<select id="country" name="country">
</select>
<table id="state" border="1">
</table> -->
<br>
Enter Text:<input type="text" id="search"/><input type="button" id="seabutton" value="Search"/>
<div id="serach">
<p>This is ankush Dapke
</p>
</div>
</body>
</html>
So the labels are populated from the database. Once the label is clicked, the label need to turn red and bold. when clicked on another label, the first label need to come back to original state and the new label should be activated and it needs to be bold and red. for some reason, the changeActiveStates() only works for the first 2 labels, i.e., when first label is clicked it turns red and when the second label is clicked the first label is turned black and the second label is turned red. when the third label is clicked, the second label remains red and the third one turns red. How do i fix this??
Here is the code:
<html>
<span>
<input type="hidden" name="LiabFilter" id= "idLib<%=liabkey %>" value="<%=liabkey %>" />
<div>
<label for="idLib<%=liabkey%>" id="liablabel" style="cursor: hand; padding-left: 25px; font-weight: normal"
onClick ="clearLiabFilter();
document.getElementById('idLib<%=liabkey%>').checked = true;
changeActiveStates(this);">
<%=liab.getName() %>
</br>
</label>
</div>
</span>
<style type="text/css">
.activate { font-weight: bold; color:#e40000;}
.visited{ font-weight: normal; color: #000000;}
</style>
<script>
function byId(id) {
return document.getElementById ? document.getElementById(id) : document.all[id];
}
var prevLink = "";
function changeActiveStates(ele) {
if (prevLink) byId(prevLink).className = '';
ele.className = 'activate';
prevLink = ele.id;
}
</script>
</html>
Are you averse to JQuery?
If not, this should work.
$('label').click(function() {
$('label').removeClass('activate'); /* Remove 'activate' class from all labels */
$(this).addClass('activate'); /* Add 'activate' class to clicked label
});
EDIT: Example on jsFiddle
EDIT: A little more detail as the questioner hasn't used JQuery before.
JQuery is a javscript library and so must be loaded by the browser before you can do all the nifty stuff.
Add the following between the <head></head> tags on your page:
<script src="http//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
(Why let google host JQuery for you?)
Then add the following, also between the tags but after the script tag given above:
$(document).ready(function() {
$('label').click(function() {
$('label').removeClass('activate'); /* Remove 'activate' class from all labels */
$(this).addClass('activate'); /* Add 'activate' class to clicked label
});
});
(What does $(document).ready() do?)
Maybe not the best of solutions, but have you considered using jQuery? It's generally not too much of a dependency , and will solve these sort of issues quite elegantly and easily for you. Plus. Cross-browser compatibility.