Monday, December 27, 2004

Add Search Word Highlighting to Your Blog

As most of the web traffic my home page receives is from web searches, I thought it would be nice to add search word highlighting to those pages. That is, whenever someone comes to those pages via a search result link (e.g., from a google search), the pages would automatically parse the referring URL and highlight the search words.

As I got to thinking about this, I realized it probably was going to be easiest to be done in client-side JavaScript rather than server-side PHP, so I went searching around for some stock JavaScript to do this, and I found some:

http://www.kryogenix.org/code/browser/searchhi/

The neat thing about this is that because it's client-side, I can use it on my blog as well. That way if my blog shows up in a google search, the page will automatically highlight all the search words.

The instructions (given on the page above) are pretty simple. You just have to be sure to add a searchword SPAN class to your style, like this:
SPAN.searchword {

background-color: yellow;
}
Now, that wasn't quite enough for me, so I modified the JavaScript given on the page above to allow me to do "in-page highlighting." That is why I now have a text box and submit button in my sidebar. You can "search" through the currently viewed page for particular words (separated by spaces); those words will then automatically be highlighted.

If you're interested in adding a similar "in-page highlighting" to your blog, view the source code of this page to see what I've done to make it happen. I've had to add a couple of JavaScript functions to my template, and I modified the original searchhi.js and stored it on my web page (the URL is in the source of this page). Of course, it still requires the STYLE addition mentioned above.


1 comment:

Ted Pavlic said...

See

Highlighting Words from Search Results :: Using JavaScript on Client-Side

for more details. I've made lots of changes to that original script. Implementation details are mentioned there. And yes, the script used on this blog is the same script mentioned on that page.