Client-side query term highlighting demo using jQuery

Yesterday, the subject of “static vs. dynamic websites” came up and an example of “something that requires dynamic page assembly” was search query term highlighting. In other words, using the HTTP Referer header (yes, it’s misspelled but that’s how it is in the spec) header and parsing it and if it’s a click-through from a search engine results page (SERP), using the search terms to highlight occurrences of them in the page.

I argued that while you could do this server-side, that this wasn’t necessary; it could be done client-side, too. In modern browsers, the “referer” (sic) information is available through JavaScript in the document.referrer (spelled correctly) variable. (NB: If you’re looking for document.referer, you’ll get frustrated. It’s actually spelled correctly in JS.)

As my suggestion to use JS and DHTML on the client-side wasn’t getting across, I decided to implement a quick proof-of-concept demo using jQuery, a fantastic JavaScript library that’s light on bytes but heavy on the features. Here’s a link to the demo:

Client-side query term highlighting demo using jQuery

Here’s the few lines of CSS and JS that makes it work:

</p> <style type="text/css"> .qterm { color: #444; background-color: #ee9; font-weight: bold; } a span.qterm { color: #00f; text-decoration: underline; } a:hover span.qterm { color: #666; } </style> <p><script language="JavaScript"> $(document).ready(function() { if (!document.referrer) return; var matches = document.referrer.match(/[?&]q=([^&]*)/); if (!matches) return; var terms = unescape(matches[1].replace(/\+/g, ' ')); var re = new RegExp().compile('(' + terms + ')', 'i'); $("body *").each(function() { if ($(this).children().size() > 0) return; if ($(this).is("xmp, pre")) return; var html = $(this).html(); var newhtml = html.replace(re, '<span class="qterm">$1</span>'); $(this).html(newhtml); }); }); </script></p> <p>

It is really that simple. Now you see why I love jQuery.

Tags:
,
,
,
,
,

Comments

  1. Why do you have to click twice for it to work correctly? Is there any way to bypass this, and just have it highlight the terms on the first pass?

  2. You need to click twice to simulate the click-through from the SERP–the HTTP referer is parsed to determine what the query terms are to highlight.

  3. Change the language=”JavaScript” to type=”text/javascript” as the language attribute doesn not exist in the spec.

  4. Ryno: You’re right, I should start using type=”text/javascript” but the “language” attribute does exist in the HTML 4.01 specification, it’s merely deprecated.

    http://www.w3.org/TR/html401/interact/scripts.html#h-18.2.1

  5. cool idea.. thanks!

Leave a Reply to Ryno Cancel reply

*