Change the color of a word in a still-editing textarea

Asked

Viewed 1,689 times

2

How do I make sure that every time the browser finds a "reserved word" in textarea, it automatically changes her color.

I want to know to make a syntax highlight.

  • 2

    As far as I know, it’s not possible to style parts of a <textarea>. The most common solution is to use a <div> with the attribute contenteditable="true"

2 answers

4


Cannot change parts of a text textarea (as well as of a input). You can apply styles (color, background, font type, size etc.) to the whole text or element, not parts of it. That’s because the textarea does not render HTML tags, and its content is treated as plain text.

What you can do is use plugins WYSIWYG replacing the textarea by a div editable and apply listeners that will detect the reserved words in the text and apply the desired color only in these words (work a little complicated, say in passing). For this you will have to search the way Javascript treats the plugin instances and do a separate programming.

Some WYSIWYG plugins available, among others, are the Tinymce and the Ckeditor.

2

Just as a complement to the @Dvd response, I show a very simplistic (and some flaws) example of how I could implement color changes of certain words using <div> with contenteditable=true:

function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

//palavras que se pretende substituir e a classe com o estilo para essas palavras
const sintaxe = [
  {
    palavra:"int",
    classe:"tipo"
  },
  {
    palavra:"if",
    classe:"base"
  }
];


$("#editor").on("keyup", function(){ //aplicar a troca para cada tecla digitada
  let cnt = $("#editor").html();

  for (s of sintaxe){ //para cada palavra aplicar a substituição no editor
    //fazer o troca da palavra por um span com mesma palavra e a classe certa
    cnt=cnt.replace(s.palavra+" ", `<span class="${s.classe}">${s.palavra}</span> `);
  }
  
  $("#editor").html(cnt); //colocar o texto substituido de volta

  //colocar o cursor no fim de novo
  placeCaretAtEnd(document.getElementById("editor"));
});
#editor {
  border:1px solid orange;
}

.tipo {
  color:darkBlue;
}

.base {
  color:purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Escreva algum texto como int x; if(x==10) {
<div id="editor" contenteditable="true"></div>

The cursor placement function at the end came from a reply on Soen and it is necessary for example to work properly, since when there is a replacement of html of <div> by javascript the cursor goes back to the beginning.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.