views:

71

answers:

1

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)?

+4  A: 

I'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.

Nick Craver