Highlight search terms automagically with JavaScript and mark

For a while I’ve been wondering how to demo the HTML5 mark element. It’s quite a funky little element, acting a bit like a highlighter pen, to draw attention to some text. The spec defines it

The mark element represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context. When used in a quotation or other block of text referred to from the prose, it indicates a highlight that was not originally present but which has been added to bring the reader’s attention to a part of the text that might not have been considered important by the original author when the block was originally written, but which is now under previously unexpected scrutiny. When used in the main prose of a document, it indicates a part of the document that has been highlighted due to its likely relevance to the user’s current activity.

Over the yule break, the answer came to me (as it so often does) as I was demolishing a bottle of red. For a couple of years now, this blog has used a script that highlights search terms if you’re referred here by Google or Yahoo. The script is written by flame-haired temptress Stuart Langridge, who describes how it works:

It checks document.referrer for a querystring with q=somethingorother in it (as Google does, and as do a host of other search engines), breaks that query up into words, and then recursively walks each node from the BODY down, once for each search word, looking for text nodes. When it finds a text node it checks to see if it contains the current search word; if it does, it replaces the current text node with three new nodes — one which is a text node containing everything before the search word, a span containing only the search word (and of class “searchword” — this is why the highlighting works!), and another text node that contains everything after the search word.

With Stuart’s permission, I simply amended the script to surround the search term(s) with the mark element rather than a span, although I’ve retained the class searchword in case you want to style these marks differently from others.

In my CSS, I just added the rule article mark {background-color:#FFC0CB;} to turn it a gentle shade of pink (my other New Year Resolution is to get in touch with my feminine side) and we have a useful demo.

As Stuart released his code with an MIT license, you can download the HTML5 version, or grab the original from his site if you like the functionality but aren’t using HTML5 yet.

As I merely changed one single line of code, all credit and Caligula-shockingly depraved offers of carnal favours should be directed to Stuart.

For more information about the mark element, see Miek Robinson’s HTML5doctor article Draw attention with mark.

20 Responses to “ Highlight search terms automagically with JavaScript and mark ”

Comment by Pete B

Neat improvement on the original.

The original script could do with a little refactoring, though, as it introduces a lot of extraneous global variables.

Comment by Schalk Neethling

Nice one Bruce! Any objection by either you or Stuart if I turn this into a Chrome extension? @Pete B – Would be cool if one could refactor the original js, maybe even throw in some jQuery goodness ;)

Maybe, with Stuart’s permission, we can host the js and extension stuff on GIT, then anyone can contribute to improving the script and extension.

Looking forward to everyone’s comments.

Comment by Bruce

Schalk, I have no objection. I assume Stuart is fine (it’s under MIT license) but you can find him on twitter as @sil.

Not sure what the jQuery is going to add to it, as it’s currently a very small script that does what it needs to do.

Comment by Bobby Jack

Using jQuery would simplify a lot of the DOM manipulation and would make the code much more readable. For example, those cryptic 7 lines at the bottom (of the original) could just be replaced with:

$(function() { searchhi.init() });

Comment by Bruce

@Bobby Jack

I suppose it just about makes sense on sites where you’re already using jQuery for other stuff. But dragging in a 20K+ library to enhance the readability of 7 lines (how many site visitors will ever read those lines?) seems unnecessary to me.

Comment by Pete B

I’ve put my take on this up on google code (tried to get Git working, but the clients for windows are hopeless!)


My updates in summary:
+ No global namespace pollution
+ Added hostname referrer check for un-conventional
search engine query parameters (i.e yahoo)
+ Now highlights the full search phrase and whole
word matches (not word sub-strings)

It’s still library agnostic, though it does use ‘jQuery(document).ready’ if available, falling back on native page load handlers.

Comment by 45 Fresh Useful JavaScript and jQuery Techniques and Tools | News, GTA, Sports, Business, Entertainment, World, Breaking - dasty.org

[...] Highlight search terms automagically with JavaScript and mark Script surrounding the search term(s) with the mark element rather than a span, although the class searchword is retained in case you want to style these marks differently from others. In the CSS, the rule article mark is just added to turn it a gentle shade of pink. [...]