iamcal.com

[home] [PDF Version]

Blog Hacks : How to highlight search words from Google

Originally published 20th June 2003

When you view a cached google page, google highlights the terms you searched for. Some people find this really useful, but it only happens when people look at the cached version, so how can you enable search term highlighting all the time? Easy - you use Javascript and the DOM.

This hack is very easy to implement. After grabbing the highlighter code (a javascript file, available at http://code.iamcal.com/js/google_highlighter/), you only need to add two lines to your template. Somewhere in the <head> section, you'll need to load the javascript file that does the highlighting:

	<script src="google.js" language="Javascript" type="text/javascript"></script>

Now that you've got the javascript loaded, you'll need to tell the browser to run the highlighter once the page has loaded. You can do this by adding an onload attribute to your <body> tag:

	<body onload="init_google();">

Your <body> tag might already have an onload attribute to trigger something else on the page:

	<body onload="foo()">

If this is the case, don't despair! You can just add the highlighter trigger after it, making sure they are seperated by a semi-colon:

	<body onload="foo(); init_google();">

You'll probably want to test this works. To do this, you'll need to type a query into google that matches one of your pages. Once you've found a match on google, click through to your page. The search term(s) should now be highlighted (you'll have to wait for the page to finish loading!).

If you'd like to see what it looks like before trying for yourself, then search for "iamcal extra" on google and follow the first match to iamcal.com

You might be wondering how this all works, and a bit of an explanation is probably in order. To understand what's going on, you'll need to look at the different javascript functions inside the google.js file.

The first function that gets called is init_google(). This function simply checks to see if the user has come from a google search page, by checking the document.referrer property.

If they have come from a search page, the init_google() function calls the next function, go_google(), which breaks the search into different words, ready for highlighting. For each term to be highlighted, the next color in the sequence is chosen to use as a highlighter, then the actual highlighting function is called.

The highlighter function, highlight_goolge(), then searches every part of the document for the term to highlight. Whenever it comes across it, it removes it from the document and replaces it with a div containing the same text, with it's background color set.