Return to Snippet

Revision: 50085
at August 9, 2011 01:20 by inreflection7


Initial Code
$("img").hover(function() {
	var originalSrc = $(this).attr('src');
	var rest = originalSrc.substring(0, originalSrc.lastIndexOf('.') );
	var last = originalSrc.substring(originalSrc.lastIndexOf('.') + 1, originalSrc.length);
	var newSrc = rest + '-color.' + last;

    $(this).attr("src", newSrc);

  }, function() {
    $(this).attr("src", $(this).attr("src").split("-color.").join("."));
  });

Initial URL

                                

Initial Description
image rollovers in jquery are usually super easy. However it sucks when working with absolute image paths - like a separate media server or CDN. Heres a quick snippet using substring and lastIndexOf to swap out the image src.

Initial Title
jQuery Image Replace using substring

Initial Tags
image, replace, jquery

Initial Language
JavaScript