How to make certain words within an editable div be of a color?

1

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>
    
asked by anonymous 04.03.2016 / 14:08

3 answers

1

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>&nbsp;");

        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

    
04.03.2016 / 14:59
1

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>';
});
    
04.03.2016 / 15:01
0

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()">
    
04.03.2016 / 14:53