/ Published in: JavaScript

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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
$("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(".")); });
Comments
