Highlighting keywords from a search can be done on the server-side, by using your development languages string replace functions, but this can add complexity to your code. This job is very well suited to client-side JavaScript. Using jQuery makes the job even easier.

The ingredients:

  1. A jQuery function to wrap and add a css class to the keywords within your content. The function described here works well: http://wpswitch.com/blog/wordpress/how-to-highlight-search-terms-with-jquery/
  2. A function to grab the keyword from the url query string.
  3. A little CSS to define how the highlighting will look.

Put it all together:

The jQuery

// include function from step 1 above here
function getParameterByName( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}
var searchQuery = getParameterByName('query');
if (searchQuery != '')
    $('#content').highlight(searchQuery, 1, 'hls');

 

The CSS

.hls { padding: 0 4px; background: #ffa; } /* highlight class */
h3 .hls { background: none; }

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *