Keyword highlighting in html Part One

Recently I posted about adding squiggly underlines to user-editable text in HTML.

By the end of the article we had nice squiggly lines appearing under text in a cross-browser way, falling back to a double underline if image borders weren’t supported. The “small” exercise left for the reader was to handle updating the text on the fly and restoring the caret position. I didn’t want to let on how much of a pain in the arse that can be! But since it is such a pain in the arse, I’m going to share the trials and tribulations with you, and by the end of this post we should have a nice working solution.

First of all let’s just review the scope of this project here:

I am NOT proprosing that you write your own WYSIWIG text editor! That is a serious endeavour and you’re better to “stand on the shoulders of giants” and use somebody else’s solution. Specifically, if you want a good code editor embedded in your HTML, look out for CodeMirror. It’s the shizzle and is very widely used, so its gonna have fewer bugs than most solutions out there. Alternatively if you’re after something a bit more like an Office-suite text box on your web page consider TinyMCE.

The solution I’m throwing up here is useful if you simply want a few specific keywords to highlight as the user types. Note that if you just want spell-check functionality, most modern browsers support the spellcheck attribute:

<input type="text" spellcheck="true"/><input type="text"/>

It’s almost always best to leave something like spell checking to the browser, because different users will have their browsers configured with different language preferences and so on. But I’m digressing…

Back to our goal which is to make something like this:

Special keywords like dyslexic and dog will be underlined magically as you type them.

Typing the words dyslexic or dog in the above input field will have them underline with our purple squiggles, other words will not be affected.

Part Two walks you through my implementation for this…