A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

jQuery: Generic Image Swap

Found this little gem in Stackoverflow.

$(function() {
        .mouseover(function() { 
            var src = $(this).attr("src").match(/[^.]+/) + "over.gif";
            $(this).attr("src", src);
        .mouseout(function() {
            var src = $(this).attr("src").replace("over", "");
            $(this).attr("src", src);

Thanks to Jarrod Dixon.

Here is another simpler version.

$(".icons_inner img").hover(
      function(){this.src = this.src.replace("_off","_on");},
      function(){this.src = this.src.replace("_on","_off");

You just have to name you email images as “my_icon_on.png” and “my_icon_off.png”. I find this version a lot simpler to implement and debug. Source.

This entry was posted in General. Bookmark the permalink.

2 Responses to jQuery: Generic Image Swap

  1. This code is OK, but I made something pretty similar but supporting fadeIn/fadeOut, + images are preloaded so they react right in time.


  2. Wenbert says:

    Thanks David! I just found a bug when I deployed my code. Will post a fix here later.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>