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 thingy will actually filter the matching query. For example, when a user types in a textbox.
$('#userInputTextbox').keypress(function(){
$('div.person').hide().filter(':contains("'+THE_QUERY+'")').show();
});
This works! And it actually filters out the stuff. My question is: how do you highlight the words that appear in there (the query and the matching text in the DIVs)?
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 thingy will actually filter the matching query. For example, when a user types in a textbox.
$('#userInputTextbox').keypress(function(){
$('div.person').hide().filter(':contains("'+THE_QUERY+'")').show();
});
This works! And it actually filters out the stuff. My question is: how do you highlight the words that appear in there (the query and the matching text in the DIVs)?
Share Improve this question asked Feb 19, 2010 at 0:39 TIMEXTIMEX 273k367 gold badges802 silver badges1.1k bronze badges 2- 1 By highlight do you mean changing the style (ie bg colour) or select the text ready for copying? – Andy E Commented Feb 19, 2010 at 0:44
-
Given that he's in a
keypress
event, he presumably wants to change a color. – SLaks Commented Feb 19, 2010 at 0:46
2 Answers
Reset to default 7I'd grab the jQuery highlight plugin for this. Using it in a project now to reflect AJAX search results, works great and very light/simple.
In your case just add .highlight(THE_QUERY)
in the chain.
$('#userInputTextbox').keypress(function(){
$('div.person').hide().removeHighlight()
.filter(':contains("'+THE_QUERY+'")').highlight(THE_QUERY).show();
});
Concept is easy, find the text wrap it in a <span class="highlight"></span>
, you can style .highlight
however you want. There's a .removeHighlight()
to match of course.
For a lenient jQuery highlight plugin you may want to consider http://frightanic./web-authoring/lenient-jquery-highlight-plugin/