jQuery Image Replace using substring


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.