Posted By

inreflection7 on 08/09/11


Tagged

image replace jquery substring


Versions (?)

jQuery Image Replace using substring


 / 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.

  1. $("img").hover(function() {
  2. var originalSrc = $(this).attr('src');
  3. var rest = originalSrc.substring(0, originalSrc.lastIndexOf('.') );
  4. var last = originalSrc.substring(originalSrc.lastIndexOf('.') + 1, originalSrc.length);
  5. var newSrc = rest + '-color.' + last;
  6.  
  7. $(this).attr("src", newSrc);
  8.  
  9. }, function() {
  10. $(this).attr("src", $(this).attr("src").split("-color.").join("."));
  11. });

Report this snippet  

You need to login to post a comment.