How to highlight a part of text in textarea

Viewed 39926

Is there a way to highlight a part of text in text-area?

Say, the text is Hi @twitter @twitpic and now I would like to highlight @twitter and @twitpic only and not Hi. Is that possible?

This has to happen on the fly.

PS: I don't want to use iFrame

Thanks in advance

4 Answers

Its pretty simple using jQuery.

HTML part:

<textarea id="test">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam rhoncus aliquam metus. Praesent vitae arcu tempor neque lacinia pretium.</textarea>
<button id="search">search</button>

JS part:

$(function(){
  $("#search").click(function(){
    var area   = $('#test');
    var findWord = "rhoncus";
    var index = area.val().indexOf(findWord);
    area.focus().prop({'selectionStart': index, 'selectionEnd': index+findWord.length})          
  })
})

Just change the variable findWord for whatever you want to highlight.

Related