JavaScript make specific letter a different color? - javascript

I am trying to make a specific letter: "*" be red in a line of JavaScript coding that I am working with.
The following is my original:
function init(){
var inp = document.getElementsByTagName('input');
for(var i = 0; i < inp.length; i++) {
if(inp[i].type == 'text','tel','number', 'email') {
inp[i].setAttribute('rel',inp[i].defaultValue)
inp[i].setAttribute('style', 'color: grey;')
inp[i].onfocus = function() {
if(this.value == this.getAttribute('rel')) {
this.value = '';
this.setAttribute('style', 'color: black;')
} else {
return false;
}
}
In order to make a specific letter red, would I change it to?
function init(){
var inp = document.getElementsByTagName('input');
for(var i = 0; i < inp.length; i++) {
if(inp[i].type == 'text','tel','number', 'email') {
inp[i].setAttribute('rel',inp[i].defaultValue)
inp[i].setAttribute('style', 'color: grey;')
inp[i].onfocus = function() {
if(this.value == this.getAttribute('rel')) {
this.value = '';
this.setAttribute('style', 'color: black;')
if(this.value == this.getAttribute('*')) {
this.setAttribute('style', 'color: red;')
} else {
return false;
}
}
How would I achieve this?

... because I am really bored, I ended up doing what you wanted using javascript.
It uses Mootools, but it should provide enough inspiration for you to recreate it using jQuery if you so desire.
function reposition() {
var position = inputEl.getPosition();
var occludeLabel = inputEl.value;
occludeLabel = occludeLabel.replace(/\*/g, '<span class="red">*</span>', 'g');
occludeEl.setStyles({
top: position.y + 1,
left: position.x + 1
});
occludeEl.set('html', occludeLabel);
}
Basically, every time you blur the input, a div containing the input box's value is placed over the input box, occluding the text. I ran a simple .replace() to replace all asterisks with a span that would turn its contents red.
Please see this jsfiddle for all of the code: http://jsfiddle.net/eTEvQ/2/

You can style only the elements but not the attributes..
This line does not make any sense..
this.value == this.getAttribute('*')
* is not a valid attribute name
Also this here is the current input element in Question..
You can set a color for the input element as a whole but not for specific characters inside them

Related

How to put this filter function into an If function?

I have the following function: http://jsfiddle.net/xznzyxyg/2/
Basically what it does it checks of the value of an input is equal to another value of another input in the same div.
Instead of the filtering I want it in an If function.
So that if true{ colour red}
The function I have now;
var inputs = $('#lol input');
var hoofdinput = document.getElementById('ad');
function Getred(i,el){
return inputs.not(this).filter(function() {
return hoofdinput.value === el.value;
}).length !== 0;
}).addClass('red');
What I want it in:
If (true){
// Colour red
}
else {
Alert('No duplicates');
}
Can somebody help me with this, I'm really frustrated with this one...
Thanks!!
EDIT: This is the solution, duplicates are coloured with red and others wich are not duplicate with green: http://jsfiddle.net/xznzyxyg/4/
is something like this what you are looking for?
var inputs = $('#lol input');
var hoofdinput = document.getElementById('ad');
for( var counter = 0; counter < inputs.length; counter++) {
if ( hoofdinput.value === inputs[counter].value )
inputs[counter].className += 'red';
else
alert('No duplicates');
}
var $inputs = $('div.myDiv input')
$inputs.each(function(i1, input1){
$inputs.slice(i1 + 1).each(function(i2, input2) {
if (input1.value == input2.value) $(input2).addClass('red');
});
});
Then if you need to alert that there were no matches
if ($('div.myDiv input.red').length == 0) alert('No duplicates');

Javascript to change innerHTML function not working

I'm building an interface that consists of 9 cells in table. When a person mouses over a cell, I want other cells to become visible, and change the text content of some of the cells. I can do that just fine if I create individual functions to change the content of each cell, but that's crazy.
I want a single function to change the text depending on the cells involved. I created a function that can take n arguments, and loops through making changes based on the arguments passed in to the function. It doesn't work.
Code for the function is below. If I call it, onMouseOver="changebox('div3')", the argument makes it to the function when I mouse over the cell. If I uncomment the document.write(cell) statement, in this instance, it prints div3 to the screen. So... why isn't it making any changes to the content of the div3 cell?
function changebox() {
for (var i = 0; i < arguments.length; i++) {
var cell = document.getElementById(arguments[i]).id;
var text = "";
if (cell == 'div3') {
text = "Reduced Travel";
} else if (cell == 'div4') {
text = "Reduced Cost";
}
//document.write(cell)
cell.innerHTML = text;
}
}
In your code cell is a string which holds the id of the object. Update the code as follows
function changebox() {
for (var i = 0; i < arguments.length; i++) {
var cell = document.getElementById(arguments[i]),
text = "";
if (cell.id == 'div3') {
text = "Reduced Travel";
} else if (cell.id == 'div4') {
text = "Reduced Cost";
}
//document.write(cell)
cell.innerHTML = text;
}
}
UPDATE :
You can reduce the code as #Tushar suggested.
No need of iterating over arguments(assuming there are only two elements, but can be modified for more elements).
function changebox() {
// As arguments is not real array, need to use call
// Check if div is present in the arguments array
var div3Index = [].indexOf.call(arguments, 'div3') > -1,
div4Index = [].indexOf.call(arguments, 'div4') > -1;
// If present then update the innerHTML of it accordingly
if (div3Index) {
document.getElementById('div3').innerHTML = 'Reduced Travel';
} else if (div4Index) {
document.getElementById('div4').innerHTML = 'Reduced Cost';
}
}
function changebox() {
var args = [].slice.call(arguments);
args.map(document.getElementById.bind(document)).forEach(setElement);
}
function setElement(ele) {
if (ele.id === 'div3') {
ele.innerHTML = "Reduced Travel";
} else if (ele.id === 'div4') {
ele.innerHTML = "Reduced Cost";
}
}
this make your function easy to be tested
As your assigning the cell variable the id of the element and changing the innerHTML of cell which is not valid .
var changeText = function() {
console.log("in change text");
for(var i= 0; i<arguments.length; i++) {
var elem = document.getElementById(arguments[i]);
var cell = document.getElementById(arguments[i]).id;
var text = "";
console.log(cell)
if (cell === "div-1") {
text = cell+" was selected!!";
} else if(cell === "div-3") {
text = cell+" was selected!!";
} else {
text = cell+" was selected";
}
elem.innerHTML = text;
}
}
This would properly change the text of div mouseovered!!

How to replace a table cell value with a picture?

I've got a table output that is generated dynamically.
I've got a javascript function that is doing some coloring and replacement of cell values, which is fine (e.g. background becomes green when innerText==3; please find the sample code below).
Now I'm trying to insert a picture in those table cells that have innerText==9.
Is it possible to include this functionality in my function?
I tried with a pictureGrey declaration an assigned it to innerText, but this doesn't work.
Does anyone have an idea, can someone help me?
Thanks a lot in advance,
Gero B.
function ModifyData( ) {
var Elements=document.getElementsByTagName('td');
pictureGrey="Z_led_grey.gif";
for(var i=0;i<Elements.length;i++) {
if(Elements[i].innerText=='3') {
Elements[i].style.color='green';
Elements[i].style.background='green';
Elements[i].innerText=' ';
}
if(Elements[i].innerText=='9') {
Elements[i].innerText= pictureGrey ;
}
}
}
please check the below code.
function ModifyData( ) {
var Elements=document.getElementsByTagName('td');
pictureGrey="Z_led_grey.gif";
for(var i=0;i<Elements.length;i++) {
if(Elements[i].innerText=='3') {
Elements[i].style.color='green';
Elements[i].style.background='green';
Elements[i].innerText=' ';
}
if(Elements[i].innerText=='9') {
Elements[i].innerText=' ';
var img = document.createElement("img");
img.src=pictureGrey;
Elements[i].appendChild (img );}
}
}
demo link:
http://jsfiddle.net/asimshahiddIT/acz5xn3b/
You could create a new image element and append it in the element. Depending on if the data can subsequently change again you might need to check for the existence of the image first.
CSS
img.myFullSizeImageClass {
width: 100%;
height: 100%;
}
JavaScript
function ModifyData() {
var Elements = document.getElementsByTagName('td');
pictureGrey = "angular-icon.png";
for (var i = 0; i < Elements.length; i++) {
if (Elements[i].firstChild.nodeValue == '3') {
Elements[i].style.color = 'green';
Elements[i].style.background = 'green';
Elements[i].firstChild.nodeValue = ' ';
}
else if (Elements[i].firstChild.nodeValue == '9') {
Elements[i].firstChild.nodeValue = "";
var img = document.createElement("img");
img.src = pictureGrey;
img.className = 'myFullSizeImageClass'
Elements[i].appendChild(img);
}
}
}

javascript - Change the font color of the last word typed

Ok I am making a text editor and have to try and make the last word typed change font color based on if it's a keyword or not... I have tried multiple solutions to this but nothing has prevailed... Here is what I have tried so far
function getLastWord() {
var input = document.getElementById("my_text").value;
//var input = document.getElementById(textArea.value);
var inputValue = input.value;
var lastWordTyped
var changeColorOfWord;
var ele = document.querySelector("#my_text");
//ele.style.color = "blue"
if (input == null) {
input == " ";
}
lastWordTyped = input.substr(input.trim().lastIndexOf(" ") + 1);
//lastWordTyped = inputValue.substr(inputValue.trim().lastIndexOf(" ") + 1);
if (input != null) {
for (var i = 0; i < reservedKeyWords.length; i++) {
if ( lastWordTyped == reservedKeyWords[i] ) {
//changeColor(lastWordTyped);
//my_text.replace(inputValue, lastWordTyped);
//ele.fieldNameElement.innerHTML = lastWordTyped;
//ele.innerHTML = lastWordTyped;
ele.innerHTML.fontcolor = 'Blue';
return;
} else if (lastWordTyped !== reservedKeyWords[i]) {
//ele.innerHTML = ele.innerHTML.replace(lastWordTyped, '<span style="color:black"></span>');
//resetFontColor();
}
}
}
}
I have tried this function (found from SO)
function changeColor(word) {
var ele = document.querySelector("my_text");
ele.onkeypress = function () {
setTimeout(function () {
//the setTimeout is so the content is inserted before execution
document.getElementById('view_text').value = ele.textContent;
if (ele.innerHTML.indexOf(word) !== -1) {
ele.innerHTML = ele.innerHTML.replace(word, '<span style="color:blue">' + word + '</span>');
}
}, 50);
}
}
Also I have tried this one:
function colorMyKeyword(keywordColor, text) {
return '<span style="color:' + keywordColor + '>' + text + '</span>';
}
None of these functions have gotten the job done though. I have it now so that it will change the text color to blue but then the problem is that it changes ALL of the text to blue after that word...
I would prefer this to be in javascript as I do not know how to use JQuery, or really CSS for that matter or even know how to write it..
Thank you for any responses.
Updated code based on comment(s) below (changed to div from input)
Not the best code in the world but it should work. The CSS should probably be done by adding a class instead of changing the style attribute.
<div id="my_text">This is some text</div>
var isKeyword = false;
var el = document.getElementById('my_text');
var arr = el.innerHTML.split(' ');
var lastWordTyped = arr.pop();
/* replace with yours*/
var reservedKeyWords = ['text','another','word', 'here'];
for (var i = 0, len = reservedKeyWords.length ; i < len ; i++) {
if ( lastWordTyped == reservedKeyWords[i] ) {
lastWordTyped = '<span style="color:blue">'+lastWordTyped +'</span>'; //update color
arr.push(lastWordTyped);
isKeyword = true;
}
}
if (!isKeyword) { arr.push(lastWordTyped); } //put original back
el.innerHTML = arr.join(' ');
UPDATED: Do the whole thing on keyup
here's a simple example that you can use: DEMO
$('#text').keyup(function(){
$('#result').html($('#text').val());
var splittedText=$('#result').html().split(/\s/);
var lastWord=splittedText[splittedText.length-1];
$('#result').html($('#result').html().replace(lastWord,'<span>'+lastWord+'</span>'));
$('#result').children('span').css('color',$('#color').val());
});
you need to write a sentence in the first input and a hexa-deciaml color in the second one.(including the # at the beginning)
Here is an attempt to answer your questions :
I am using #GaryStorey's answer as it was a better starting point than what I add (I do like pop&push).
The problem with his answer were that it only showed how to change the color but it wasn't relevant on how to do it in an input nor in a contenteditable element.
So here are my adjustements, with a setCaret function to deal with the fact that caret always returns to start if we do change the innerHTML of edited element.
Be carefull, it is still very buggy and you should not use it in any production,
however it can give you a good starting point.
var reservedKeyWords = ['text', 'another', 'word', 'here'];
var el = document.getElementById('my_text');
el.addEventListener('keyup', function (evt) {
if (evt.keyCode == 32 || evt.keyCode == 13) {
var isKeyword = false;
var arr = el.innerHTML.split(/\s/);
var lastWordTyped = arr.pop();
lastWordTyped = lastWordTyped.replace(' ', '');
for (var i = 0, len = reservedKeyWords.length; i < len; i++) {
if (lastWordTyped == reservedKeyWords[i]) {
lastWordTyped = '<span style="color:blue">' + lastWordTyped + '</span>'; //update color
arr.push(lastWordTyped);
isKeyword = true;
}
}
if (!isKeyword) {
arr.push(lastWordTyped);
} //put original back
el.innerHTML = arr.join(' ') + ' ';
setCaret(el);
}
});
function setCaret(el) {
var range = document.createRange();
var endNode = el.lastChild;
range.selectNodeContents(endNode);
range.setStart(endNode, range.endOffset);
range.setEnd(endNode, range.endOffset);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
#my_text {
min-width: 100%;
min-height: 2em;
padding: 0.5em;
display: block;
border : dashed 0.5px grey;
}
<p> list of KeyWords : 'text', 'another', 'word', 'here';</p>
<span id="my_text" contenteditable="true">Edit me using "reservedKeyWords" defined in JS</span>
Oh and note that I am using a span instead of a div, because div tag adds some <br> from nowhere after the textNode.

Using labels like HTML5 placeholder

I am trying to use <label> elements in my html contact form like the HTML5 placeholder attribute for inputs. I have written the following JavaScript to to act as a reusable function witch will provide the following functionality.
Find the input by name.
Get the value of the input.
Find the label belonging to the input.
Change the label style depending on the state of the input.
Change the label style depending on the value of the input.
However it is not working and I don't know why as no errors appear in the console. What am I doing wrong? here is a JS Fiddle with code
function placeholder(field_name) {
// Get the input box with field_name
// Then get input value
var box = document.getElementsByName(field_name);
var i;
for (i = 0; i < box.length; i++) {
var value = document.getElementById(box[i].value);
}
// Get the labels belonging to each box using the HTML for attribute
var labels = document.getElementsByTagName('LABEL');
for (i = 0; i < labels.length; i++) {
if (labels[i].htmlFor !== '') {
var elem = document.getElementById(labels[i].htmlFor);
if (elem) {
box.label = labels[i];
}
}
}
// Colors
var focusColor = "#D5D5D5";
var blurColor = "#B3B3B3";
// If no text is in the box then show the label grey color
box.onblur = function () {
box.label.style.color = blurColor;
};
// If input focuses change label color to light grey
box.onfocus = function () {
box.label.style.color = focusColor;
};
// If there is text in the box then hide the label
if (box.value !== "") {
// Quick do something, hide!
box.label.style.color = "transparent";
}
}
// Call the function passing field names as parameters
placeholder(document.getElementsByName("email"));
placeholder(document.getElementsByName("firstName"));
placeholder(document.getElementsByName("lastName"));
This might be considered a little overkill on the number of listeners I've used, feel free to remove any you think unnecessary, but I've tried to employ your HTML structure as you have it and give you all desired effects. It should work for either the <label>s for matching the <input>s id OR matching it's <name> (given no id matches). I'll always say prefer using an id over name. I believe this JavaScript should also work in all browsers too, except the addEventListener for which you'd need a shim for old IE versions (let me know if it doesn't in one/the error message).
Demo
var focusColor = "#D5D5D5", blurColor = "#B3B3B3";
function placeholder(fieldName) {
var named = document.getElementsByName(fieldName), i;
for (i = 0; i < named.length; ++i) { // loop over all elements with this name
(function (n) { // catch in scope
var labels = [], tmp, j, fn, focus, blur;
if ('labels' in n && n.labels.length > 0) labels = n.labels; // if labels provided by browser use it
else { // get labels from form, filter to ones we want
tmp = n.form.getElementsByTagName('label');
for (j = 0;j < tmp.length; ++j) {
if (tmp[j].htmlFor === fieldName) {
labels.push(tmp[j]);
}
}
}
for (j = 0; j < labels.length; ++j) { // loop over each label
(function (label) { // catch label in scope
fn = function () {
if (this.value === '') {
label.style.visibility = 'visible';
} else {
label.style.visibility = 'hidden';
}
};
focus = function () {
label.style.color = focusColor;
};
blur = function () {
label.style.color = blurColor;
};
}(labels[j]));
n.addEventListener('click', fn); // add to relevant listeners
n.addEventListener('keydown', fn);
n.addEventListener('keypress', fn);
n.addEventListener('keyup', fn);
n.addEventListener('focus', fn);
n.addEventListener('focus', focus);
n.addEventListener('blur', fn);
n.addEventListener('blur', blur);
}
}(named[i]));
}
};
placeholder("email"); // just pass the name attribute
placeholder("firstName");
placeholder("lastName");
http://jsfiddle.net/cCxjk/5/
var inputs = document.getElementsByTagName('input');
var old_ele = '';
var old_label ='';
function hide_label(ele){
var id_of_input = ele.target.id;
var label = document.getElementById(id_of_input + '-placeholder');
if(ele.target == document.activeElement){
label.style.display = 'none';
}
if (old_ele.value == '' && old_ele != document.activeElement){
old_label.style.display = 'inline';
}
old_ele = ele.target;
old_label = label;
}
for(var i = 0; i < inputs.length; i++){
inputs[i].addEventListener('click', hide_label);
}
I will point out a couple things, you will have to find away around the fact that the label is inside the input so users now can't click on half of the input and actually have the input gain focus.
Also I guess you want to do this in IE (otherwise I would strongly advise using the html5 placeholder!) which means you would need to change the ele.target to ele.srcElement.

Categories