Simple jQuery image rollover script

Just a simple script I use to automate image rollovers that may be of use to others. Just include this javascript:


UPDATED

I felt motivated to simplify this even more according to many of the comments below. This takes advantage of html5 data attributes instead of a custom one, and eliminates the need for a special hover css class. It also eliminates the need for a temporary variable to store the current image in by using a ‘tmp’ attribute, and then removing it when finished. It also preloads the images for the rollover.

$(function() {
	$('img[data-hover]').hover(function() {
		$(this).attr('tmp', $(this).attr('src')).attr('src', $(this).attr('data-hover')).attr('data-hover', $(this).attr('tmp')).removeAttr('tmp');
	}).each(function() {
		$('<img />').attr('src', $(this).attr('data-hover'));
	});;
});

This should be used with an img element as follows:

<img src="first.gif" data-hover="second.gif" />

Original code

$(function() {
	$('.rollover').hover(function() {
		var currentImg = $(this).attr('src');
		$(this).attr('src', $(this).attr('hover'));
		$(this).attr('hover', currentImg);
	}, function() {
		var currentImg = $(this).attr('src');
		$(this).attr('src', $(this).attr('hover'));
		$(this).attr('hover', currentImg);
	});
});

This will pick up an image that looks as follows, and setup the rollover image:

<img src="first.gif" hover="second.gif"  class="rollover"/>
  • del.icio.us
  • Digg
  • Facebook
  • Reddit
  • Twitter
  • Yahoo! Buzz
and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

54 Comments

  1. mk
    Posted August 2, 2011 at 2:02 am | Permalink

    Hi!
    wonderfull script!
    I need an help to modify it to return the original image onmouseout, can you help me?
    Thanks

  2. Posted August 16, 2011 at 2:17 am | Permalink

    Thank u, its usefull

  3. Posted January 1, 2012 at 5:59 pm | Permalink

    Great script, solved a problem I was having with my normal JavaScript equivalent and did it in less than 1/4 of the code!

  4. Posted February 2, 2012 at 11:02 am | Permalink

    Works! This is better than some of the other (more bloated) hover/swap scripts out there. I wan’t sure at first…. because the demo is missing (or I couldn’t find it)! Thanks Brad

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Page optimized by WP Minify WordPress Plugin