JavaScript
Article

jQuery Hover Highlight Script

By Sam Deering

Hi guys, I’ve written this jQuery script which highlights any element on the page (by changing the background colour). It’s a clever little script which will save you lots of time if you have many elements that require mouse hover events.

Features

  • Specify a background colour for hover when mouse hovers element
  • Retains background colour when mouse leaves element

Usage

Demo

The following divs have been given class=”displayItem” and hover with an orange background.

Transparent backgrounds (only in FireFox)

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu nulla leo. Proin ligula nunc, lacinia pellentesque bibendum ac.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu nulla leo. Proin ligula nunc, lacinia pellentesque bibendum ac.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu nulla leo. Proin ligula nunc, lacinia pellentesque bibendum ac.

Coloured backgrounds (all browsers)

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu nulla leo. Proin ligula nunc, lacinia pellentesque bibendum ac.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu nulla leo. Proin ligula nunc, lacinia pellentesque bibendum ac.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc eu nulla leo. Proin ligula nunc, lacinia pellentesque bibendum ac.

jQuery.hoverHighlight()

I’ve tested the script on the different browsers and fixed IE6 & IE7 bug (they don’t support the jQuery.data method so I’ve coded in a default value for those browsers that don’t support it). So now it works on all browsers.

You’ll also need this script to convert the colours from RGB to Hex.

/*
 *	Create Hover Backgound Highlight for any element. 
 *	Retains original background-color.
 */
$.fn.extend({
	hoverHighlight: function (colour) 
	{
		$(this).live('mouseenter', function() 
		{
			/*save original background colour*/
			if ($(this).css('background-color') && $(this).css('background-color') !== 'transparent')
			{
				$(this).data('bgColour',rgb2hex($(this).css('background-color')));
			}
			else {
				$(this).data('bgColour','transparent');
			}
			$(this).css('background-color',colour);
		}).live('mouseleave', function() 
		{ 
			var defaultBg = 'transparent';
			var changeBg = ($(this).data('bgColour') !== null) ? $(this).data('bgColour') : defaultBg;
			$(this).css('background-color',changeBg);
		});
		return this; /*enable jQuery chaining*/
	}
});

Full Code For Demo Above

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.