I have a DIV
that is editable by the user, but I wanted it when I typed Brasil
it is only this green word tabem as EUA
is red, but only certain words.
DIV code:
<div id="texto" contenteditable = "true" ></ div>
I have a DIV
that is editable by the user, but I wanted it when I typed Brasil
it is only this green word tabem as EUA
is red, but only certain words.
DIV code:
<div id="texto" contenteditable = "true" ></ div>
You can pick up the keyup event and search the text if there is an occurrence of the word, existing this word in the text simply replace it by doing a replace, as the name itself says, and add some tag to include your style.
You can improve it in many ways, but you could base it on something like:
HTML:
<div id="text" contenteditable="true">O </ div>
JS:
var text = document.getElementById('text');
text.onkeyup = function(evt) {
var counter = this.textContent.split(/(Brasil)/i).length;
if (counter > 1 && (!this.lastCount || this.lastCount < counter) ) {
this.lastCount = counter;
this.innerHTML = this.textContent.replace(/(Brasil)/g, "<b class='green'>Brasil</b> ");
var range = document.createRange();
var sel = window.getSelection();
var lastNode = text.childNodes.item(text.childNodes.length -1)
range.setStart(lastNode, 1);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
};
CSS:
.green{
color:green;
}
See working at jsfiddle
As I mentioned in the comment, I do not know which event you would use to call the function. But finding, one option is: when saving the text, use the replace with regular expression to insert span elements around the words, with the corresponding styles.
var palavrasCores = {Brasil: "green", EUA: "red"};
var resultado = textoObtido.replace(/Brasil|EUA/gi, function(palavra){
return '<span style="color: ' + palavrasCores[palavra] + '">' + palavra + '</span>';
});
function checkKey() {
var plaintext = document.getElementById("textbox");
if(plaintext.value == 'EUA') {
plaintext.style.color = "#FF0000";
}
if(plaintext.value == 'BRASIL') {
plaintext.style.color = "#66CD00";
}
if(plaintext.value != 'EUA' && plaintext.value != 'BRASIL') {
plaintext.style.color = "#000000";
}
}
</script>
<input type="text" id="textbox" name="plaintext" onKeyUp="checkKey()">