Textarea Syntax Highlighting Test

This is a test for the Hiss game editor.

There is a <textarea> containing some JavaScript source. Rendered below it is a <div> containing the same text with background colors used to "syntax highlight" some JavaScript keywords, etc.

This was written by hand, but with liberal use of these two excellent resources:

Try it out! Change stuff below and scroll the textarea. The syntax highlighting should change with it seamlessly. This works because browsers are pretty amazing.

Where's the code?

The script in the textarea above is all of the code on this page. So there you go!

The important styles are the use of absolute positioning and z-index to take the textarea and the highlighting div out of the regular document flow so they can overlap each other.

Here's just the vital stuff:

/* Apply to both the textarea and the highlights div */
#ta, #hl {
    white-space: pre-wrap;
    word-wrap: break-word;
    position: absolute;
    box-sizing: border-box;
}

/* textarea */
#ta {
    background-color: transparent;
    z-index: 2;
}

/* highlights div */
#hl {
    z-index: 1;
    overflow: auto;
    pointer-events: none;
}

Highlighting is done by putting markup tags around pieces of the text in the highlighting div and then applying background colors to those tags. The background colors show through the transparent textarea.

Note: If you want to use colored text rather than background colors for your highlighting, you'll need to swap the z-index of the textarea and highlight div and swap the transparency of the backgrounds (and text color). I was personally a little leery about doing that because if anything fails, the textarea is not longer usable. So I went with the background color highlighting instead.

View the source of this page for the whole thing.

Back to Ratfactor.com