pgr4567
pgr4567

Reputation: 73

Highlight words in input field html

I want some kind of input field in html like textarea, or a div which is editable to highlight special words like Hi or foo. I know that there are some syntax highlighting script out there - Prettify, Syntax Highlighter, highlight.js, etc. However would have to adapt them pretty heavily, because "HI" isn't a token in a programming language. I don't know how to do this / code one by myself.

(I've thought of some kind of string.split by chars and then adding those chars together until I have "HI" for example, but I don't know how to color those words then. span with color? But how would I remove that span if the word is deleted?)

Do you have advice?

Thanks in advance

Upvotes: 2

Views: 5131

Answers (1)

Seth McClaine
Seth McClaine

Reputation: 10030

Heres a simple example in JSFiddle (Note updates on blur)

JSFiddle

https://jsfiddle.net/ug7xmgx0/3/

HTML

<div id="textInput" type="text"contenteditable="true">
 Example on foo bar
</div>

JS

$(document).ready(function () {
  var handleChange = function(e) {
    var newVal = '';
        var words = $('div').text().split(' ');
    $(words).each(function(key, val){
      newVal += `<span class="${val}">${val}</span> `;
    });
    $('div').html(newVal);
  };
  $('div').blur(handleChange);
  handleChange();
});

CSS

.on {
  color: red;
}
.foo {
  color: yellow;
}

There are a ton of ways to do this. This is a real simple way to do it, but isn't super efficient or focused on UX.

Upvotes: 2

Related Questions