views:

185

answers:

2

Hey all,

I'm trying to create a textarea that will highlight some keywords as the user types in there. I understant textarea can only support plain text and that I have to use a 'rich text' editor in order to achieve this. I would like something really simple though and not the bloated 'rich editors' out there. Any ideas?

Thanks!

+1  A: 

Here is a snippet that gives you the basics of what are looking for:

<style>
    .textarea { font-family:arial; font-size:12px; border:0; width:700px; height:200px; }
    .realTextarea { margin:0; background:transparent; position: absolute; z-index:999; }
    .overlayTextarea { margin:0; position:absolute; top:1; left:1; z-index:998; }
    .textareaBorder { border:groove 1px #ccc; position:relative; width:702px; height:202px; }
    .highlight { background: yellow; }
</style>

<script>
    var _terms = ['January', 'February', 'March']; // YOUR SEARCH TERMS GO HERE //

    function preg_quote( str ) {
        return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
    }

    function doit() {
        var s = myTextarea.innerHTML;

        for (i=0; i<_terms.length; i++)
            s = s.replace( new RegExp( preg_quote( _terms[i] ), 'gi' ), '<span class="highlight">' + _terms[i] + '</span>' );

        myOtherTextarea.innerHTML = s.replace( new RegExp( preg_quote( '\r' ), 'gi' ), '<br>' );
    }
</script>

<div class="textarea textareaBorder">
    <textarea id="myTextarea" onkeyup="doit();" class="textarea realTextarea"></textarea>
    <div id="myOtherTextarea" class="textarea overlayTextarea"></div>
</div>

The basic concept is that the <textarea> (on top) is transparent and the <div> underneath contains the "rich / hightlighted" version. There is room for improvement when it comes to wrapping text but you get the idea. Happy Highlighting!

Credit: The preg_quote function is from Kevin van Zonneveld http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_preg_quote/

Todd H.
+1  A: 

Take a look at this one : http://codemirror.net/

Yanick Rochon