How to use jQuery to highlight text
Suppose I have this HTML code:
<div class="person"> Mike Mulky </div> <div class="person"> Jenny Sun </div> <div class="person"> Jack Kickle </div> This jQuery thing will actually filter the corresponding query. For example, when a user enters a text field.
$('#userInputTextbox').keypress(function(){ $('div.person').hide().filter(':contains("'+THE_QUERY+'")').show(); }); It works! And it actually filters out the material. My question is: how do you highlight the words that appear there (query and corresponding text in a DIV)?
I would grab a jQuery highlight plugin for this. Using it in the project now to reflect AJAX search results works fine and very easy / simple.
In your case, just add .highlight(THE_QUERY) to the chain.
$('#userInputTextbox').keypress(function(){ $('div.person').hide().removeHighlight() .filter(':contains("'+THE_QUERY+'")').highlight(THE_QUERY).show(); }); The concept is simple, find the text, wrap it in <span class="highlight"></span> , you can style .highlight , but you want to. There .removeHighlight() to match, of course.
For a lightweight jQuery highlighting plugin, you can consider http://frightanic.com/web-authoring/lenient-jquery-highlight-plugin/