jQuery Image Comparison

09 Sep 2010

I just created a silly jQuery plugin to compare two images for my HDR comparison post. All it does is toggle which image is visible in a container on mouseover/mouseout. It's not really the most useful behavior imagined - I guess I wrote it more of a showcase of how easy it is to author jQuery plugins. You can see a working demonstration here.

To use it just put two images in a container and call compare() on the selector:

  <div class="compare">               
    <img src="/images/photos/IMG_0805.JPG" alt="Regular" />
    <img src="/images/photos/IMG_0806.JPG" alt="HDR" />
  </div>
  $(document).ready(function(){
    $('.compare').compare();
  });

Here is the plugin code:

  (function($){ 
  	$.fn.compare = function(options)
  	{
  		$(this).each(function(index, one){
  			var first = $(one).find('img:first');
  			var other = $(one).find('img:last');

  			//Hide all but the first:
  			$(one).find('img').hide();
  			first.show();

  			$(one).mouseover(function(){
  				first.hide();
  				other.show();
  			}).mouseout(function(){
  				other.hide();
  				first.show();
  			});
  		});

  	}
  })(jQuery);

Download Code