Change the image source on rollover using jQuery





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







442















I have a few images and their rollover images. Using jQuery, I want to show/hide the rollover image when the onmousemove/onmouseout event happen. All my image names follow the same pattern, like this:




Original Image: Image.gif



Rollover Image: Imageover.gif




I want to insert and remove the "over" portion of image source in the onmouseover and onmouseout event, respectively.



How can I do it using jQuery?










share|improve this question

























  • I wrote a small how-to with examples for beginners, Change image with JavaScript (or jQuery). There's also an example without using jQuery.

    – gothy
    Aug 9 '10 at 20:44













  • Change image on mouseover dotnetspeaks.com/DisplayArticle.aspx?ID=89

    – Sumit
    Dec 7 '10 at 8:15






  • 10





    Just what I'm looking for. Thanks for posting the Question!

    – Samuel Meddows
    Feb 18 '11 at 6:40











  • I have a problem like this(My Question). The answer of this question is great but in IE9 every time that you goes over button, there is additional request for image and it is very bad. Is any body has better answer?

    – Iman
    May 16 '12 at 8:51




















442















I have a few images and their rollover images. Using jQuery, I want to show/hide the rollover image when the onmousemove/onmouseout event happen. All my image names follow the same pattern, like this:




Original Image: Image.gif



Rollover Image: Imageover.gif




I want to insert and remove the "over" portion of image source in the onmouseover and onmouseout event, respectively.



How can I do it using jQuery?










share|improve this question

























  • I wrote a small how-to with examples for beginners, Change image with JavaScript (or jQuery). There's also an example without using jQuery.

    – gothy
    Aug 9 '10 at 20:44













  • Change image on mouseover dotnetspeaks.com/DisplayArticle.aspx?ID=89

    – Sumit
    Dec 7 '10 at 8:15






  • 10





    Just what I'm looking for. Thanks for posting the Question!

    – Samuel Meddows
    Feb 18 '11 at 6:40











  • I have a problem like this(My Question). The answer of this question is great but in IE9 every time that you goes over button, there is additional request for image and it is very bad. Is any body has better answer?

    – Iman
    May 16 '12 at 8:51
















442












442








442


83






I have a few images and their rollover images. Using jQuery, I want to show/hide the rollover image when the onmousemove/onmouseout event happen. All my image names follow the same pattern, like this:




Original Image: Image.gif



Rollover Image: Imageover.gif




I want to insert and remove the "over" portion of image source in the onmouseover and onmouseout event, respectively.



How can I do it using jQuery?










share|improve this question
















I have a few images and their rollover images. Using jQuery, I want to show/hide the rollover image when the onmousemove/onmouseout event happen. All my image names follow the same pattern, like this:




Original Image: Image.gif



Rollover Image: Imageover.gif




I want to insert and remove the "over" portion of image source in the onmouseover and onmouseout event, respectively.



How can I do it using jQuery?







jquery html






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 18 '16 at 10:12









lowtechsun

84011340




84011340










asked Feb 12 '09 at 7:28









Sachin GaurSachin Gaur

5,80292934




5,80292934













  • I wrote a small how-to with examples for beginners, Change image with JavaScript (or jQuery). There's also an example without using jQuery.

    – gothy
    Aug 9 '10 at 20:44













  • Change image on mouseover dotnetspeaks.com/DisplayArticle.aspx?ID=89

    – Sumit
    Dec 7 '10 at 8:15






  • 10





    Just what I'm looking for. Thanks for posting the Question!

    – Samuel Meddows
    Feb 18 '11 at 6:40











  • I have a problem like this(My Question). The answer of this question is great but in IE9 every time that you goes over button, there is additional request for image and it is very bad. Is any body has better answer?

    – Iman
    May 16 '12 at 8:51





















  • I wrote a small how-to with examples for beginners, Change image with JavaScript (or jQuery). There's also an example without using jQuery.

    – gothy
    Aug 9 '10 at 20:44













  • Change image on mouseover dotnetspeaks.com/DisplayArticle.aspx?ID=89

    – Sumit
    Dec 7 '10 at 8:15






  • 10





    Just what I'm looking for. Thanks for posting the Question!

    – Samuel Meddows
    Feb 18 '11 at 6:40











  • I have a problem like this(My Question). The answer of this question is great but in IE9 every time that you goes over button, there is additional request for image and it is very bad. Is any body has better answer?

    – Iman
    May 16 '12 at 8:51



















I wrote a small how-to with examples for beginners, Change image with JavaScript (or jQuery). There's also an example without using jQuery.

– gothy
Aug 9 '10 at 20:44







I wrote a small how-to with examples for beginners, Change image with JavaScript (or jQuery). There's also an example without using jQuery.

– gothy
Aug 9 '10 at 20:44















Change image on mouseover dotnetspeaks.com/DisplayArticle.aspx?ID=89

– Sumit
Dec 7 '10 at 8:15





Change image on mouseover dotnetspeaks.com/DisplayArticle.aspx?ID=89

– Sumit
Dec 7 '10 at 8:15




10




10





Just what I'm looking for. Thanks for posting the Question!

– Samuel Meddows
Feb 18 '11 at 6:40





Just what I'm looking for. Thanks for posting the Question!

– Samuel Meddows
Feb 18 '11 at 6:40













I have a problem like this(My Question). The answer of this question is great but in IE9 every time that you goes over button, there is additional request for image and it is very bad. Is any body has better answer?

– Iman
May 16 '12 at 8:51







I have a problem like this(My Question). The answer of this question is great but in IE9 every time that you goes over button, there is additional request for image and it is very bad. Is any body has better answer?

– Iman
May 16 '12 at 8:51














14 Answers
14






active

oldest

votes


















618














To set up on ready:



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


For those that use url image sources:



$(function() {
$("img")
.mouseover(function() {
var src = $(this).attr("src");
var regex = /_normal.svg/gi;
src = this.src.replace(regex,'_rollover.svg');
$(this).attr("src", src);

})
.mouseout(function() {
var src = $(this).attr("src");
var regex = /_rollover.svg/gi;
src = this.src.replace(regex,'_normal.svg');
$(this).attr("src", src);

});
});





share|improve this answer





















  • 7





    This doesnt work if the src is an absolute url with a . in it (like www.example.com)

    – Kieran Andrews
    Feb 22 '11 at 23:32






  • 8





    This also doesn't work if you use a domain like www.over.com, or have over somewhere else in the URI.

    – Benjamin Manns
    Apr 4 '11 at 17:32






  • 32





    may I suggest editing the final .replace with .replace("over.gif", ".gif");

    – Nathan Koop
    Sep 13 '11 at 15:34






  • 2





    Thanks for posting this. I hope you don't mind that I put this on my blog. My blog is like a "notebook" and it's my "go-to-thing" when I forget something.

    – wenbert
    Sep 16 '11 at 8:00






  • 4





    The images work only if they are already in cache.

    – sonnb
    Jul 13 '12 at 5:01



















113














I know you're asking about using jQuery, but you can achieve the same effect in browsers that have JavaScript turned off using CSS:



#element {
width: 100px; /* width of image */
height: 200px; /* height of image */
background-image: url(/path/to/image.jpg);
}

#element:hover {
background-image: url(/path/to/other_image.jpg);
}


There's a longer description here



Even better, however, is to use sprites: simple-css-image-rollover






share|improve this answer





















  • 1





    yeah, but is little harder to do this on IMAGE elements :) Besides that, CSS mean the separation of content from presentation. If you do this, you join those things ;) You can't have this for a large site, right?

    – Ionuț Staicu
    Feb 12 '09 at 7:56











  • I agree with you about the css, but it seems the question author wanted a generic solution that applies to multiple images all at once.

    – Jarrod Dixon
    Feb 12 '09 at 7:56






  • 9





    This solution is the most preferable option, unless you are doing some effects. I was thinking the exact same thing +1

    – Angel.King.47
    May 22 '11 at 14:29






  • 6





    It is the best solution. To avoid waiting for the new image (network request) use a single image.jpg and play with background-position to show / hide the good one.

    – iwalktheline
    Sep 7 '11 at 10:46






  • 2





    @kheraud Moving a single image is a good solution, but whether it's the best or not depends on the image size. For example, on slow internet, downloading two 1920px wide images in one gigantic file would take unacceptably long. For icons and small images though it works fine.

    – DACrosby
    Apr 29 '12 at 5:50



















61














If you have more than one image and you need something generic that doesn't depend on a naming convention.



HTML



<img data-other-src="big-zebra.jpg" src="small-cat.jpg">
<img data-other-src="huge-elephant.jpg" src="white-mouse.jpg">
<img data-other-src="friendly-bear.jpg" src="penguin.jpg">


JavaScript



$('img').bind('mouseenter mouseleave', function() {
$(this).attr({
src: $(this).attr('data-other-src')
, 'data-other-src': $(this).attr('src')
})
});





share|improve this answer





















  • 1





    This was the one for me. Just remember to put the javascript inside a function to execute it ie when DOM ready "$(function(){ });"

    – Mischa
    Sep 27 '12 at 4:05













  • Actually it triggers when the page is still loading, and when your mouse cursor is actually over the selector it replaces the url so then the effect is inverted

    – Mike
    Aug 31 '16 at 10:38



















57














    /* Teaser image swap function */
$('img.swap').hover(function () {
this.src = '/images/signup_big_hover.png';
}, function () {
this.src = '/images/signup_big.png';
});





share|improve this answer



















  • 4





    Keep in mind that going this way will mean that the user will see a pause on first hover while the browser fetches the image.

    – Tyson
    Jun 26 '12 at 3:51






  • 1





    @Tyson Hate to hop onto the train late, but you can preload the images by either via Javascript or CSS

    – cubrr
    Feb 12 '14 at 16:45








  • 1





    This worked with Chrome, but not with Firefox. :(

    – tehlivi
    Jun 19 '15 at 15:13











  • Doesn't work on Chrome 37 neither. $(this).attr("src", src) works fine.

    – Le Droid
    Jan 27 '16 at 22:17



















24





+25









A generic solution that doesn't limit you to "this image" and "that image" only may be to add the 'onmouseover' and 'onmouseout' tags to the HTML code itself.



HTML



<img src="img1.jpg" onmouseover="swap('img2.jpg')" onmouseout="swap('img1.jpg')" />


JavaScript



function swap(newImg){
this.src = newImg;
}




Depending on your setup, maybe something like this would work better (and requires less HTML modification).



HTML



<img src="img1.jpg" id="ref1" />
<img src="img3.jpg" id="ref2" />
<img src="img5.jpg" id="ref3" />


JavaScript / jQuery



// Declare Arrays
imgList = new Array();
imgList["ref1"] = new Array();
imgList["ref2"] = new Array();
imgList["ref3"] = new Array();

//Set values for each mouse state
imgList["ref1"]["out"] = "img1.jpg";
imgList["ref1"]["over"] = "img2.jpg";
imgList["ref2"]["out"] = "img3.jpg";
imgList["ref2"]["over"] = "img4.jpg";
imgList["ref3"]["out"] = "img5.jpg";
imgList["ref3"]["over"] = "img6.jpg";

//Add the swapping functions
$("img").mouseover(function(){
$(this).attr("src", imgList[ $(this).attr("id") ]["over"]);
}

$("img").mouseout(function(){
$(this).attr("src", imgList[ $(this).attr("id") ]["out"]);
}





share|improve this answer

































    21














    $('img.over').each(function(){
    var t=$(this);
    var src1= t.attr('src'); // initial src
    var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
    t.hover(function(){
    $(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension
    }, function(){
    $(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
    });
    });


    You may want to change the class of images from first line. If you need more image classes (or different path) you may use



    $('img.over, #container img, img.anotherOver').each(function(){


    and so on.



    It should work, I didn't test it :)






    share|improve this answer





















    • 2





      +1 Doh, forgot about the hover event helper! And nice suggestion about adding a class to the images - truly is a best practice :)

      – Jarrod Dixon
      Feb 12 '09 at 8:05






    • 1





      That's far better solution because it caches the old image source.

      – trante
      Jun 29 '12 at 20:23











    • The negative part is, if the image is in the bottom of the page and there is 10-20 images then layout becomes weird.

      – trante
      Jun 29 '12 at 20:24



















    13














    I was hoping for an über one liner like:



    $("img.screenshot").attr("src", $(this).replace("foo", "bar"));





    share|improve this answer

































      6














      If the solution you are looking for is for an animated button, then the best you can do to improve in performance is the combination of sprites and CSS. A sprite is a huge image that contains all the images from your site (header, logo, buttons, and all decorations you have). Each image you have uses an HTTP request, and the more HTTP requests the more time it will take to load.



      .buttonClass {
      width: 25px;
      height: 25px;
      background: url(Sprite.gif) -40px -500px;
      }
      .buttonClass:hover {
      width: 25px;
      height: 25px;
      background: url(Sprite.gif) -40px -525px;
      }


      The 0px 0px coordinates will be the left upper corner from your sprites.



      But if you are developing some photo album with Ajax or something like that, then JavaScript (or any framework) is the best.



      Have fun!






      share|improve this answer

































        4














        $('img').mouseover(function(){
        var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
        $(this).attr("src", newSrc);
        });
        $('img').mouseout(function(){
        var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
        $(this).attr("src", newSrc);
        });





        share|improve this answer































          4














          Whilst looking for a solution some time back, I found a similar script to the below, which after some tweaking I got working for me.



          It handles two images, that almost always default to "off", where the mouse is off the image (image-example_off.jpg), and the occasional "on", where for the times the mouse is hovered, the required alternative image (image-example_on.jpg) is displayed.



          <script type="text/javascript">        
          $(document).ready(function() {
          $("img", this).hover(swapImageIn, swapImageOut);

          function swapImageIn(e) {
          this.src = this.src.replace("_off", "_on");
          }
          function swapImageOut (e) {
          this.src = this.src.replace("_on", "_off");
          }
          });
          </script>





          share|improve this answer


























          • I realise that the above function would execute for all images within the DOM as it is currently coded. Supplying further context would make it focus the effect to specific img elements.

            – Kristopher Rout
            Sep 5 '12 at 22:50



















          3














          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
          <html xmlns="http://www.w3.org/1999/xhtml">
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
          <title>JQuery</title>
          <script src="jquery.js" type="text/javascript"> </script>
          <style type="text/css">
          #box{
          width: 68px;
          height: 27px;
          background: url(images/home1.gif);
          cursor: pointer;
          }
          </style>

          <script type="text/javascript">

          $(function(){

          $('#box').hover( function(){
          $('#box').css('background', 'url(images/home2.gif)');

          });
          $('#box').mouseout( function(){
          $('#box').css('background', 'url(images/home1.gif)');

          });

          });
          </script>
          </head>

          <body>
          <div id="box" onclick="location.href='index.php';"></div>
          </body>
          </html>





          share|improve this answer

































            2














            I've made something like the following code :)



            It works only, when you have a second file named with _hover, for example, facebook.png and facebook_hover.png



            $('#social').find('a').hover(function() {
            var target = $(this).find('img').attr('src');
            //console.log(target);
            var newTarg = target.replace('.png', '_hover.png');
            $(this).find('img').attr("src", newTarg);
            }, function() {
            var target = $(this).find('img').attr('src');
            var newTarg = target.replace('_hover.png', '.png');
            $(this).find('img').attr("src", newTarg);
            });





            share|improve this answer

































              1














              <img src="img1.jpg" data-swap="img2.jpg"/>



              img = {

              init: function() {
              $('img').on('mouseover', img.swap);
              $('img').on('mouseover', img.swap);
              },

              swap: function() {
              var tmp = $(this).data('swap');
              $(this).attr('data-swap', $(this).attr('src'));
              $(this).attr('str', tmp);
              }
              }

              img.init();





              share|improve this answer































                1














                Adapted from Richard Ayotte's code -
                To target an img in a ul/li list (found via wrapper div class here), something like this:



                $('div.navlist li').bind('mouseenter mouseleave', function() {    
                $(this).find('img').attr({ src: $(this).find('img').attr('data-alt-src'),
                'data-alt-src':$(this).find('img').attr('src') }
                );





                share|improve this answer
























                  Your Answer






                  StackExchange.ifUsing("editor", function () {
                  StackExchange.using("externalEditor", function () {
                  StackExchange.using("snippets", function () {
                  StackExchange.snippets.init();
                  });
                  });
                  }, "code-snippets");

                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "1"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: true,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: 10,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f540349%2fchange-the-image-source-on-rollover-using-jquery%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  14 Answers
                  14






                  active

                  oldest

                  votes








                  14 Answers
                  14






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  618














                  To set up on ready:



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


                  For those that use url image sources:



                  $(function() {
                  $("img")
                  .mouseover(function() {
                  var src = $(this).attr("src");
                  var regex = /_normal.svg/gi;
                  src = this.src.replace(regex,'_rollover.svg');
                  $(this).attr("src", src);

                  })
                  .mouseout(function() {
                  var src = $(this).attr("src");
                  var regex = /_rollover.svg/gi;
                  src = this.src.replace(regex,'_normal.svg');
                  $(this).attr("src", src);

                  });
                  });





                  share|improve this answer





















                  • 7





                    This doesnt work if the src is an absolute url with a . in it (like www.example.com)

                    – Kieran Andrews
                    Feb 22 '11 at 23:32






                  • 8





                    This also doesn't work if you use a domain like www.over.com, or have over somewhere else in the URI.

                    – Benjamin Manns
                    Apr 4 '11 at 17:32






                  • 32





                    may I suggest editing the final .replace with .replace("over.gif", ".gif");

                    – Nathan Koop
                    Sep 13 '11 at 15:34






                  • 2





                    Thanks for posting this. I hope you don't mind that I put this on my blog. My blog is like a "notebook" and it's my "go-to-thing" when I forget something.

                    – wenbert
                    Sep 16 '11 at 8:00






                  • 4





                    The images work only if they are already in cache.

                    – sonnb
                    Jul 13 '12 at 5:01
















                  618














                  To set up on ready:



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


                  For those that use url image sources:



                  $(function() {
                  $("img")
                  .mouseover(function() {
                  var src = $(this).attr("src");
                  var regex = /_normal.svg/gi;
                  src = this.src.replace(regex,'_rollover.svg');
                  $(this).attr("src", src);

                  })
                  .mouseout(function() {
                  var src = $(this).attr("src");
                  var regex = /_rollover.svg/gi;
                  src = this.src.replace(regex,'_normal.svg');
                  $(this).attr("src", src);

                  });
                  });





                  share|improve this answer





















                  • 7





                    This doesnt work if the src is an absolute url with a . in it (like www.example.com)

                    – Kieran Andrews
                    Feb 22 '11 at 23:32






                  • 8





                    This also doesn't work if you use a domain like www.over.com, or have over somewhere else in the URI.

                    – Benjamin Manns
                    Apr 4 '11 at 17:32






                  • 32





                    may I suggest editing the final .replace with .replace("over.gif", ".gif");

                    – Nathan Koop
                    Sep 13 '11 at 15:34






                  • 2





                    Thanks for posting this. I hope you don't mind that I put this on my blog. My blog is like a "notebook" and it's my "go-to-thing" when I forget something.

                    – wenbert
                    Sep 16 '11 at 8:00






                  • 4





                    The images work only if they are already in cache.

                    – sonnb
                    Jul 13 '12 at 5:01














                  618












                  618








                  618







                  To set up on ready:



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


                  For those that use url image sources:



                  $(function() {
                  $("img")
                  .mouseover(function() {
                  var src = $(this).attr("src");
                  var regex = /_normal.svg/gi;
                  src = this.src.replace(regex,'_rollover.svg');
                  $(this).attr("src", src);

                  })
                  .mouseout(function() {
                  var src = $(this).attr("src");
                  var regex = /_rollover.svg/gi;
                  src = this.src.replace(regex,'_normal.svg');
                  $(this).attr("src", src);

                  });
                  });





                  share|improve this answer















                  To set up on ready:



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


                  For those that use url image sources:



                  $(function() {
                  $("img")
                  .mouseover(function() {
                  var src = $(this).attr("src");
                  var regex = /_normal.svg/gi;
                  src = this.src.replace(regex,'_rollover.svg');
                  $(this).attr("src", src);

                  })
                  .mouseout(function() {
                  var src = $(this).attr("src");
                  var regex = /_rollover.svg/gi;
                  src = this.src.replace(regex,'_normal.svg');
                  $(this).attr("src", src);

                  });
                  });






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 4 at 4:41









                  jemmamariex3

                  4210




                  4210










                  answered Feb 12 '09 at 7:31









                  Jarrod DixonJarrod Dixon

                  13.6k95470




                  13.6k95470








                  • 7





                    This doesnt work if the src is an absolute url with a . in it (like www.example.com)

                    – Kieran Andrews
                    Feb 22 '11 at 23:32






                  • 8





                    This also doesn't work if you use a domain like www.over.com, or have over somewhere else in the URI.

                    – Benjamin Manns
                    Apr 4 '11 at 17:32






                  • 32





                    may I suggest editing the final .replace with .replace("over.gif", ".gif");

                    – Nathan Koop
                    Sep 13 '11 at 15:34






                  • 2





                    Thanks for posting this. I hope you don't mind that I put this on my blog. My blog is like a "notebook" and it's my "go-to-thing" when I forget something.

                    – wenbert
                    Sep 16 '11 at 8:00






                  • 4





                    The images work only if they are already in cache.

                    – sonnb
                    Jul 13 '12 at 5:01














                  • 7





                    This doesnt work if the src is an absolute url with a . in it (like www.example.com)

                    – Kieran Andrews
                    Feb 22 '11 at 23:32






                  • 8





                    This also doesn't work if you use a domain like www.over.com, or have over somewhere else in the URI.

                    – Benjamin Manns
                    Apr 4 '11 at 17:32






                  • 32





                    may I suggest editing the final .replace with .replace("over.gif", ".gif");

                    – Nathan Koop
                    Sep 13 '11 at 15:34






                  • 2





                    Thanks for posting this. I hope you don't mind that I put this on my blog. My blog is like a "notebook" and it's my "go-to-thing" when I forget something.

                    – wenbert
                    Sep 16 '11 at 8:00






                  • 4





                    The images work only if they are already in cache.

                    – sonnb
                    Jul 13 '12 at 5:01








                  7




                  7





                  This doesnt work if the src is an absolute url with a . in it (like www.example.com)

                  – Kieran Andrews
                  Feb 22 '11 at 23:32





                  This doesnt work if the src is an absolute url with a . in it (like www.example.com)

                  – Kieran Andrews
                  Feb 22 '11 at 23:32




                  8




                  8





                  This also doesn't work if you use a domain like www.over.com, or have over somewhere else in the URI.

                  – Benjamin Manns
                  Apr 4 '11 at 17:32





                  This also doesn't work if you use a domain like www.over.com, or have over somewhere else in the URI.

                  – Benjamin Manns
                  Apr 4 '11 at 17:32




                  32




                  32





                  may I suggest editing the final .replace with .replace("over.gif", ".gif");

                  – Nathan Koop
                  Sep 13 '11 at 15:34





                  may I suggest editing the final .replace with .replace("over.gif", ".gif");

                  – Nathan Koop
                  Sep 13 '11 at 15:34




                  2




                  2





                  Thanks for posting this. I hope you don't mind that I put this on my blog. My blog is like a "notebook" and it's my "go-to-thing" when I forget something.

                  – wenbert
                  Sep 16 '11 at 8:00





                  Thanks for posting this. I hope you don't mind that I put this on my blog. My blog is like a "notebook" and it's my "go-to-thing" when I forget something.

                  – wenbert
                  Sep 16 '11 at 8:00




                  4




                  4





                  The images work only if they are already in cache.

                  – sonnb
                  Jul 13 '12 at 5:01





                  The images work only if they are already in cache.

                  – sonnb
                  Jul 13 '12 at 5:01













                  113














                  I know you're asking about using jQuery, but you can achieve the same effect in browsers that have JavaScript turned off using CSS:



                  #element {
                  width: 100px; /* width of image */
                  height: 200px; /* height of image */
                  background-image: url(/path/to/image.jpg);
                  }

                  #element:hover {
                  background-image: url(/path/to/other_image.jpg);
                  }


                  There's a longer description here



                  Even better, however, is to use sprites: simple-css-image-rollover






                  share|improve this answer





















                  • 1





                    yeah, but is little harder to do this on IMAGE elements :) Besides that, CSS mean the separation of content from presentation. If you do this, you join those things ;) You can't have this for a large site, right?

                    – Ionuț Staicu
                    Feb 12 '09 at 7:56











                  • I agree with you about the css, but it seems the question author wanted a generic solution that applies to multiple images all at once.

                    – Jarrod Dixon
                    Feb 12 '09 at 7:56






                  • 9





                    This solution is the most preferable option, unless you are doing some effects. I was thinking the exact same thing +1

                    – Angel.King.47
                    May 22 '11 at 14:29






                  • 6





                    It is the best solution. To avoid waiting for the new image (network request) use a single image.jpg and play with background-position to show / hide the good one.

                    – iwalktheline
                    Sep 7 '11 at 10:46






                  • 2





                    @kheraud Moving a single image is a good solution, but whether it's the best or not depends on the image size. For example, on slow internet, downloading two 1920px wide images in one gigantic file would take unacceptably long. For icons and small images though it works fine.

                    – DACrosby
                    Apr 29 '12 at 5:50
















                  113














                  I know you're asking about using jQuery, but you can achieve the same effect in browsers that have JavaScript turned off using CSS:



                  #element {
                  width: 100px; /* width of image */
                  height: 200px; /* height of image */
                  background-image: url(/path/to/image.jpg);
                  }

                  #element:hover {
                  background-image: url(/path/to/other_image.jpg);
                  }


                  There's a longer description here



                  Even better, however, is to use sprites: simple-css-image-rollover






                  share|improve this answer





















                  • 1





                    yeah, but is little harder to do this on IMAGE elements :) Besides that, CSS mean the separation of content from presentation. If you do this, you join those things ;) You can't have this for a large site, right?

                    – Ionuț Staicu
                    Feb 12 '09 at 7:56











                  • I agree with you about the css, but it seems the question author wanted a generic solution that applies to multiple images all at once.

                    – Jarrod Dixon
                    Feb 12 '09 at 7:56






                  • 9





                    This solution is the most preferable option, unless you are doing some effects. I was thinking the exact same thing +1

                    – Angel.King.47
                    May 22 '11 at 14:29






                  • 6





                    It is the best solution. To avoid waiting for the new image (network request) use a single image.jpg and play with background-position to show / hide the good one.

                    – iwalktheline
                    Sep 7 '11 at 10:46






                  • 2





                    @kheraud Moving a single image is a good solution, but whether it's the best or not depends on the image size. For example, on slow internet, downloading two 1920px wide images in one gigantic file would take unacceptably long. For icons and small images though it works fine.

                    – DACrosby
                    Apr 29 '12 at 5:50














                  113












                  113








                  113







                  I know you're asking about using jQuery, but you can achieve the same effect in browsers that have JavaScript turned off using CSS:



                  #element {
                  width: 100px; /* width of image */
                  height: 200px; /* height of image */
                  background-image: url(/path/to/image.jpg);
                  }

                  #element:hover {
                  background-image: url(/path/to/other_image.jpg);
                  }


                  There's a longer description here



                  Even better, however, is to use sprites: simple-css-image-rollover






                  share|improve this answer















                  I know you're asking about using jQuery, but you can achieve the same effect in browsers that have JavaScript turned off using CSS:



                  #element {
                  width: 100px; /* width of image */
                  height: 200px; /* height of image */
                  background-image: url(/path/to/image.jpg);
                  }

                  #element:hover {
                  background-image: url(/path/to/other_image.jpg);
                  }


                  There's a longer description here



                  Even better, however, is to use sprites: simple-css-image-rollover







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Sep 8 '17 at 11:24









                  ankit suthar

                  2,31462242




                  2,31462242










                  answered Feb 12 '09 at 7:54









                  TysonTyson

                  5,44322836




                  5,44322836








                  • 1





                    yeah, but is little harder to do this on IMAGE elements :) Besides that, CSS mean the separation of content from presentation. If you do this, you join those things ;) You can't have this for a large site, right?

                    – Ionuț Staicu
                    Feb 12 '09 at 7:56











                  • I agree with you about the css, but it seems the question author wanted a generic solution that applies to multiple images all at once.

                    – Jarrod Dixon
                    Feb 12 '09 at 7:56






                  • 9





                    This solution is the most preferable option, unless you are doing some effects. I was thinking the exact same thing +1

                    – Angel.King.47
                    May 22 '11 at 14:29






                  • 6





                    It is the best solution. To avoid waiting for the new image (network request) use a single image.jpg and play with background-position to show / hide the good one.

                    – iwalktheline
                    Sep 7 '11 at 10:46






                  • 2





                    @kheraud Moving a single image is a good solution, but whether it's the best or not depends on the image size. For example, on slow internet, downloading two 1920px wide images in one gigantic file would take unacceptably long. For icons and small images though it works fine.

                    – DACrosby
                    Apr 29 '12 at 5:50














                  • 1





                    yeah, but is little harder to do this on IMAGE elements :) Besides that, CSS mean the separation of content from presentation. If you do this, you join those things ;) You can't have this for a large site, right?

                    – Ionuț Staicu
                    Feb 12 '09 at 7:56











                  • I agree with you about the css, but it seems the question author wanted a generic solution that applies to multiple images all at once.

                    – Jarrod Dixon
                    Feb 12 '09 at 7:56






                  • 9





                    This solution is the most preferable option, unless you are doing some effects. I was thinking the exact same thing +1

                    – Angel.King.47
                    May 22 '11 at 14:29






                  • 6





                    It is the best solution. To avoid waiting for the new image (network request) use a single image.jpg and play with background-position to show / hide the good one.

                    – iwalktheline
                    Sep 7 '11 at 10:46






                  • 2





                    @kheraud Moving a single image is a good solution, but whether it's the best or not depends on the image size. For example, on slow internet, downloading two 1920px wide images in one gigantic file would take unacceptably long. For icons and small images though it works fine.

                    – DACrosby
                    Apr 29 '12 at 5:50








                  1




                  1





                  yeah, but is little harder to do this on IMAGE elements :) Besides that, CSS mean the separation of content from presentation. If you do this, you join those things ;) You can't have this for a large site, right?

                  – Ionuț Staicu
                  Feb 12 '09 at 7:56





                  yeah, but is little harder to do this on IMAGE elements :) Besides that, CSS mean the separation of content from presentation. If you do this, you join those things ;) You can't have this for a large site, right?

                  – Ionuț Staicu
                  Feb 12 '09 at 7:56













                  I agree with you about the css, but it seems the question author wanted a generic solution that applies to multiple images all at once.

                  – Jarrod Dixon
                  Feb 12 '09 at 7:56





                  I agree with you about the css, but it seems the question author wanted a generic solution that applies to multiple images all at once.

                  – Jarrod Dixon
                  Feb 12 '09 at 7:56




                  9




                  9





                  This solution is the most preferable option, unless you are doing some effects. I was thinking the exact same thing +1

                  – Angel.King.47
                  May 22 '11 at 14:29





                  This solution is the most preferable option, unless you are doing some effects. I was thinking the exact same thing +1

                  – Angel.King.47
                  May 22 '11 at 14:29




                  6




                  6





                  It is the best solution. To avoid waiting for the new image (network request) use a single image.jpg and play with background-position to show / hide the good one.

                  – iwalktheline
                  Sep 7 '11 at 10:46





                  It is the best solution. To avoid waiting for the new image (network request) use a single image.jpg and play with background-position to show / hide the good one.

                  – iwalktheline
                  Sep 7 '11 at 10:46




                  2




                  2





                  @kheraud Moving a single image is a good solution, but whether it's the best or not depends on the image size. For example, on slow internet, downloading two 1920px wide images in one gigantic file would take unacceptably long. For icons and small images though it works fine.

                  – DACrosby
                  Apr 29 '12 at 5:50





                  @kheraud Moving a single image is a good solution, but whether it's the best or not depends on the image size. For example, on slow internet, downloading two 1920px wide images in one gigantic file would take unacceptably long. For icons and small images though it works fine.

                  – DACrosby
                  Apr 29 '12 at 5:50











                  61














                  If you have more than one image and you need something generic that doesn't depend on a naming convention.



                  HTML



                  <img data-other-src="big-zebra.jpg" src="small-cat.jpg">
                  <img data-other-src="huge-elephant.jpg" src="white-mouse.jpg">
                  <img data-other-src="friendly-bear.jpg" src="penguin.jpg">


                  JavaScript



                  $('img').bind('mouseenter mouseleave', function() {
                  $(this).attr({
                  src: $(this).attr('data-other-src')
                  , 'data-other-src': $(this).attr('src')
                  })
                  });





                  share|improve this answer





















                  • 1





                    This was the one for me. Just remember to put the javascript inside a function to execute it ie when DOM ready "$(function(){ });"

                    – Mischa
                    Sep 27 '12 at 4:05













                  • Actually it triggers when the page is still loading, and when your mouse cursor is actually over the selector it replaces the url so then the effect is inverted

                    – Mike
                    Aug 31 '16 at 10:38
















                  61














                  If you have more than one image and you need something generic that doesn't depend on a naming convention.



                  HTML



                  <img data-other-src="big-zebra.jpg" src="small-cat.jpg">
                  <img data-other-src="huge-elephant.jpg" src="white-mouse.jpg">
                  <img data-other-src="friendly-bear.jpg" src="penguin.jpg">


                  JavaScript



                  $('img').bind('mouseenter mouseleave', function() {
                  $(this).attr({
                  src: $(this).attr('data-other-src')
                  , 'data-other-src': $(this).attr('src')
                  })
                  });





                  share|improve this answer





















                  • 1





                    This was the one for me. Just remember to put the javascript inside a function to execute it ie when DOM ready "$(function(){ });"

                    – Mischa
                    Sep 27 '12 at 4:05













                  • Actually it triggers when the page is still loading, and when your mouse cursor is actually over the selector it replaces the url so then the effect is inverted

                    – Mike
                    Aug 31 '16 at 10:38














                  61












                  61








                  61







                  If you have more than one image and you need something generic that doesn't depend on a naming convention.



                  HTML



                  <img data-other-src="big-zebra.jpg" src="small-cat.jpg">
                  <img data-other-src="huge-elephant.jpg" src="white-mouse.jpg">
                  <img data-other-src="friendly-bear.jpg" src="penguin.jpg">


                  JavaScript



                  $('img').bind('mouseenter mouseleave', function() {
                  $(this).attr({
                  src: $(this).attr('data-other-src')
                  , 'data-other-src': $(this).attr('src')
                  })
                  });





                  share|improve this answer















                  If you have more than one image and you need something generic that doesn't depend on a naming convention.



                  HTML



                  <img data-other-src="big-zebra.jpg" src="small-cat.jpg">
                  <img data-other-src="huge-elephant.jpg" src="white-mouse.jpg">
                  <img data-other-src="friendly-bear.jpg" src="penguin.jpg">


                  JavaScript



                  $('img').bind('mouseenter mouseleave', function() {
                  $(this).attr({
                  src: $(this).attr('data-other-src')
                  , 'data-other-src': $(this).attr('src')
                  })
                  });






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 23 '12 at 1:52

























                  answered Feb 19 '12 at 14:23









                  Richard AyotteRichard Ayotte

                  3,87212533




                  3,87212533








                  • 1





                    This was the one for me. Just remember to put the javascript inside a function to execute it ie when DOM ready "$(function(){ });"

                    – Mischa
                    Sep 27 '12 at 4:05













                  • Actually it triggers when the page is still loading, and when your mouse cursor is actually over the selector it replaces the url so then the effect is inverted

                    – Mike
                    Aug 31 '16 at 10:38














                  • 1





                    This was the one for me. Just remember to put the javascript inside a function to execute it ie when DOM ready "$(function(){ });"

                    – Mischa
                    Sep 27 '12 at 4:05













                  • Actually it triggers when the page is still loading, and when your mouse cursor is actually over the selector it replaces the url so then the effect is inverted

                    – Mike
                    Aug 31 '16 at 10:38








                  1




                  1





                  This was the one for me. Just remember to put the javascript inside a function to execute it ie when DOM ready "$(function(){ });"

                  – Mischa
                  Sep 27 '12 at 4:05







                  This was the one for me. Just remember to put the javascript inside a function to execute it ie when DOM ready "$(function(){ });"

                  – Mischa
                  Sep 27 '12 at 4:05















                  Actually it triggers when the page is still loading, and when your mouse cursor is actually over the selector it replaces the url so then the effect is inverted

                  – Mike
                  Aug 31 '16 at 10:38





                  Actually it triggers when the page is still loading, and when your mouse cursor is actually over the selector it replaces the url so then the effect is inverted

                  – Mike
                  Aug 31 '16 at 10:38











                  57














                      /* Teaser image swap function */
                  $('img.swap').hover(function () {
                  this.src = '/images/signup_big_hover.png';
                  }, function () {
                  this.src = '/images/signup_big.png';
                  });





                  share|improve this answer



















                  • 4





                    Keep in mind that going this way will mean that the user will see a pause on first hover while the browser fetches the image.

                    – Tyson
                    Jun 26 '12 at 3:51






                  • 1





                    @Tyson Hate to hop onto the train late, but you can preload the images by either via Javascript or CSS

                    – cubrr
                    Feb 12 '14 at 16:45








                  • 1





                    This worked with Chrome, but not with Firefox. :(

                    – tehlivi
                    Jun 19 '15 at 15:13











                  • Doesn't work on Chrome 37 neither. $(this).attr("src", src) works fine.

                    – Le Droid
                    Jan 27 '16 at 22:17
















                  57














                      /* Teaser image swap function */
                  $('img.swap').hover(function () {
                  this.src = '/images/signup_big_hover.png';
                  }, function () {
                  this.src = '/images/signup_big.png';
                  });





                  share|improve this answer



















                  • 4





                    Keep in mind that going this way will mean that the user will see a pause on first hover while the browser fetches the image.

                    – Tyson
                    Jun 26 '12 at 3:51






                  • 1





                    @Tyson Hate to hop onto the train late, but you can preload the images by either via Javascript or CSS

                    – cubrr
                    Feb 12 '14 at 16:45








                  • 1





                    This worked with Chrome, but not with Firefox. :(

                    – tehlivi
                    Jun 19 '15 at 15:13











                  • Doesn't work on Chrome 37 neither. $(this).attr("src", src) works fine.

                    – Le Droid
                    Jan 27 '16 at 22:17














                  57












                  57








                  57







                      /* Teaser image swap function */
                  $('img.swap').hover(function () {
                  this.src = '/images/signup_big_hover.png';
                  }, function () {
                  this.src = '/images/signup_big.png';
                  });





                  share|improve this answer













                      /* Teaser image swap function */
                  $('img.swap').hover(function () {
                  this.src = '/images/signup_big_hover.png';
                  }, function () {
                  this.src = '/images/signup_big.png';
                  });






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Aug 2 '09 at 19:53









                  jonasljonasl

                  2,42632024




                  2,42632024








                  • 4





                    Keep in mind that going this way will mean that the user will see a pause on first hover while the browser fetches the image.

                    – Tyson
                    Jun 26 '12 at 3:51






                  • 1





                    @Tyson Hate to hop onto the train late, but you can preload the images by either via Javascript or CSS

                    – cubrr
                    Feb 12 '14 at 16:45








                  • 1





                    This worked with Chrome, but not with Firefox. :(

                    – tehlivi
                    Jun 19 '15 at 15:13











                  • Doesn't work on Chrome 37 neither. $(this).attr("src", src) works fine.

                    – Le Droid
                    Jan 27 '16 at 22:17














                  • 4





                    Keep in mind that going this way will mean that the user will see a pause on first hover while the browser fetches the image.

                    – Tyson
                    Jun 26 '12 at 3:51






                  • 1





                    @Tyson Hate to hop onto the train late, but you can preload the images by either via Javascript or CSS

                    – cubrr
                    Feb 12 '14 at 16:45








                  • 1





                    This worked with Chrome, but not with Firefox. :(

                    – tehlivi
                    Jun 19 '15 at 15:13











                  • Doesn't work on Chrome 37 neither. $(this).attr("src", src) works fine.

                    – Le Droid
                    Jan 27 '16 at 22:17








                  4




                  4





                  Keep in mind that going this way will mean that the user will see a pause on first hover while the browser fetches the image.

                  – Tyson
                  Jun 26 '12 at 3:51





                  Keep in mind that going this way will mean that the user will see a pause on first hover while the browser fetches the image.

                  – Tyson
                  Jun 26 '12 at 3:51




                  1




                  1





                  @Tyson Hate to hop onto the train late, but you can preload the images by either via Javascript or CSS

                  – cubrr
                  Feb 12 '14 at 16:45







                  @Tyson Hate to hop onto the train late, but you can preload the images by either via Javascript or CSS

                  – cubrr
                  Feb 12 '14 at 16:45






                  1




                  1





                  This worked with Chrome, but not with Firefox. :(

                  – tehlivi
                  Jun 19 '15 at 15:13





                  This worked with Chrome, but not with Firefox. :(

                  – tehlivi
                  Jun 19 '15 at 15:13













                  Doesn't work on Chrome 37 neither. $(this).attr("src", src) works fine.

                  – Le Droid
                  Jan 27 '16 at 22:17





                  Doesn't work on Chrome 37 neither. $(this).attr("src", src) works fine.

                  – Le Droid
                  Jan 27 '16 at 22:17











                  24





                  +25









                  A generic solution that doesn't limit you to "this image" and "that image" only may be to add the 'onmouseover' and 'onmouseout' tags to the HTML code itself.



                  HTML



                  <img src="img1.jpg" onmouseover="swap('img2.jpg')" onmouseout="swap('img1.jpg')" />


                  JavaScript



                  function swap(newImg){
                  this.src = newImg;
                  }




                  Depending on your setup, maybe something like this would work better (and requires less HTML modification).



                  HTML



                  <img src="img1.jpg" id="ref1" />
                  <img src="img3.jpg" id="ref2" />
                  <img src="img5.jpg" id="ref3" />


                  JavaScript / jQuery



                  // Declare Arrays
                  imgList = new Array();
                  imgList["ref1"] = new Array();
                  imgList["ref2"] = new Array();
                  imgList["ref3"] = new Array();

                  //Set values for each mouse state
                  imgList["ref1"]["out"] = "img1.jpg";
                  imgList["ref1"]["over"] = "img2.jpg";
                  imgList["ref2"]["out"] = "img3.jpg";
                  imgList["ref2"]["over"] = "img4.jpg";
                  imgList["ref3"]["out"] = "img5.jpg";
                  imgList["ref3"]["over"] = "img6.jpg";

                  //Add the swapping functions
                  $("img").mouseover(function(){
                  $(this).attr("src", imgList[ $(this).attr("id") ]["over"]);
                  }

                  $("img").mouseout(function(){
                  $(this).attr("src", imgList[ $(this).attr("id") ]["out"]);
                  }





                  share|improve this answer






























                    24





                    +25









                    A generic solution that doesn't limit you to "this image" and "that image" only may be to add the 'onmouseover' and 'onmouseout' tags to the HTML code itself.



                    HTML



                    <img src="img1.jpg" onmouseover="swap('img2.jpg')" onmouseout="swap('img1.jpg')" />


                    JavaScript



                    function swap(newImg){
                    this.src = newImg;
                    }




                    Depending on your setup, maybe something like this would work better (and requires less HTML modification).



                    HTML



                    <img src="img1.jpg" id="ref1" />
                    <img src="img3.jpg" id="ref2" />
                    <img src="img5.jpg" id="ref3" />


                    JavaScript / jQuery



                    // Declare Arrays
                    imgList = new Array();
                    imgList["ref1"] = new Array();
                    imgList["ref2"] = new Array();
                    imgList["ref3"] = new Array();

                    //Set values for each mouse state
                    imgList["ref1"]["out"] = "img1.jpg";
                    imgList["ref1"]["over"] = "img2.jpg";
                    imgList["ref2"]["out"] = "img3.jpg";
                    imgList["ref2"]["over"] = "img4.jpg";
                    imgList["ref3"]["out"] = "img5.jpg";
                    imgList["ref3"]["over"] = "img6.jpg";

                    //Add the swapping functions
                    $("img").mouseover(function(){
                    $(this).attr("src", imgList[ $(this).attr("id") ]["over"]);
                    }

                    $("img").mouseout(function(){
                    $(this).attr("src", imgList[ $(this).attr("id") ]["out"]);
                    }





                    share|improve this answer




























                      24





                      +25







                      24





                      +25



                      24




                      +25





                      A generic solution that doesn't limit you to "this image" and "that image" only may be to add the 'onmouseover' and 'onmouseout' tags to the HTML code itself.



                      HTML



                      <img src="img1.jpg" onmouseover="swap('img2.jpg')" onmouseout="swap('img1.jpg')" />


                      JavaScript



                      function swap(newImg){
                      this.src = newImg;
                      }




                      Depending on your setup, maybe something like this would work better (and requires less HTML modification).



                      HTML



                      <img src="img1.jpg" id="ref1" />
                      <img src="img3.jpg" id="ref2" />
                      <img src="img5.jpg" id="ref3" />


                      JavaScript / jQuery



                      // Declare Arrays
                      imgList = new Array();
                      imgList["ref1"] = new Array();
                      imgList["ref2"] = new Array();
                      imgList["ref3"] = new Array();

                      //Set values for each mouse state
                      imgList["ref1"]["out"] = "img1.jpg";
                      imgList["ref1"]["over"] = "img2.jpg";
                      imgList["ref2"]["out"] = "img3.jpg";
                      imgList["ref2"]["over"] = "img4.jpg";
                      imgList["ref3"]["out"] = "img5.jpg";
                      imgList["ref3"]["over"] = "img6.jpg";

                      //Add the swapping functions
                      $("img").mouseover(function(){
                      $(this).attr("src", imgList[ $(this).attr("id") ]["over"]);
                      }

                      $("img").mouseout(function(){
                      $(this).attr("src", imgList[ $(this).attr("id") ]["out"]);
                      }





                      share|improve this answer















                      A generic solution that doesn't limit you to "this image" and "that image" only may be to add the 'onmouseover' and 'onmouseout' tags to the HTML code itself.



                      HTML



                      <img src="img1.jpg" onmouseover="swap('img2.jpg')" onmouseout="swap('img1.jpg')" />


                      JavaScript



                      function swap(newImg){
                      this.src = newImg;
                      }




                      Depending on your setup, maybe something like this would work better (and requires less HTML modification).



                      HTML



                      <img src="img1.jpg" id="ref1" />
                      <img src="img3.jpg" id="ref2" />
                      <img src="img5.jpg" id="ref3" />


                      JavaScript / jQuery



                      // Declare Arrays
                      imgList = new Array();
                      imgList["ref1"] = new Array();
                      imgList["ref2"] = new Array();
                      imgList["ref3"] = new Array();

                      //Set values for each mouse state
                      imgList["ref1"]["out"] = "img1.jpg";
                      imgList["ref1"]["over"] = "img2.jpg";
                      imgList["ref2"]["out"] = "img3.jpg";
                      imgList["ref2"]["over"] = "img4.jpg";
                      imgList["ref3"]["out"] = "img5.jpg";
                      imgList["ref3"]["over"] = "img6.jpg";

                      //Add the swapping functions
                      $("img").mouseover(function(){
                      $(this).attr("src", imgList[ $(this).attr("id") ]["over"]);
                      }

                      $("img").mouseout(function(){
                      $(this).attr("src", imgList[ $(this).attr("id") ]["out"]);
                      }






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Sep 11 '13 at 19:56

























                      answered Apr 12 '12 at 4:53









                      DACrosbyDACrosby

                      8,40632643




                      8,40632643























                          21














                          $('img.over').each(function(){
                          var t=$(this);
                          var src1= t.attr('src'); // initial src
                          var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
                          t.hover(function(){
                          $(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension
                          }, function(){
                          $(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
                          });
                          });


                          You may want to change the class of images from first line. If you need more image classes (or different path) you may use



                          $('img.over, #container img, img.anotherOver').each(function(){


                          and so on.



                          It should work, I didn't test it :)






                          share|improve this answer





















                          • 2





                            +1 Doh, forgot about the hover event helper! And nice suggestion about adding a class to the images - truly is a best practice :)

                            – Jarrod Dixon
                            Feb 12 '09 at 8:05






                          • 1





                            That's far better solution because it caches the old image source.

                            – trante
                            Jun 29 '12 at 20:23











                          • The negative part is, if the image is in the bottom of the page and there is 10-20 images then layout becomes weird.

                            – trante
                            Jun 29 '12 at 20:24
















                          21














                          $('img.over').each(function(){
                          var t=$(this);
                          var src1= t.attr('src'); // initial src
                          var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
                          t.hover(function(){
                          $(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension
                          }, function(){
                          $(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
                          });
                          });


                          You may want to change the class of images from first line. If you need more image classes (or different path) you may use



                          $('img.over, #container img, img.anotherOver').each(function(){


                          and so on.



                          It should work, I didn't test it :)






                          share|improve this answer





















                          • 2





                            +1 Doh, forgot about the hover event helper! And nice suggestion about adding a class to the images - truly is a best practice :)

                            – Jarrod Dixon
                            Feb 12 '09 at 8:05






                          • 1





                            That's far better solution because it caches the old image source.

                            – trante
                            Jun 29 '12 at 20:23











                          • The negative part is, if the image is in the bottom of the page and there is 10-20 images then layout becomes weird.

                            – trante
                            Jun 29 '12 at 20:24














                          21












                          21








                          21







                          $('img.over').each(function(){
                          var t=$(this);
                          var src1= t.attr('src'); // initial src
                          var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
                          t.hover(function(){
                          $(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension
                          }, function(){
                          $(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
                          });
                          });


                          You may want to change the class of images from first line. If you need more image classes (or different path) you may use



                          $('img.over, #container img, img.anotherOver').each(function(){


                          and so on.



                          It should work, I didn't test it :)






                          share|improve this answer















                          $('img.over').each(function(){
                          var t=$(this);
                          var src1= t.attr('src'); // initial src
                          var newSrc = src1.substring(0, src1.lastIndexOf('.'));; // let's get file name without extension
                          t.hover(function(){
                          $(this).attr('src', newSrc+ '-over.' + /[^.]+$/.exec(src1)); //last part is for extension
                          }, function(){
                          $(this).attr('src', newSrc + '.' + /[^.]+$/.exec(src1)); //removing '-over' from the name
                          });
                          });


                          You may want to change the class of images from first line. If you need more image classes (or different path) you may use



                          $('img.over, #container img, img.anotherOver').each(function(){


                          and so on.



                          It should work, I didn't test it :)







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 15 '11 at 14:40









                          pawelmech

                          24724




                          24724










                          answered Feb 12 '09 at 7:51









                          Ionuț StaicuIonuț Staicu

                          11.6k104457




                          11.6k104457








                          • 2





                            +1 Doh, forgot about the hover event helper! And nice suggestion about adding a class to the images - truly is a best practice :)

                            – Jarrod Dixon
                            Feb 12 '09 at 8:05






                          • 1





                            That's far better solution because it caches the old image source.

                            – trante
                            Jun 29 '12 at 20:23











                          • The negative part is, if the image is in the bottom of the page and there is 10-20 images then layout becomes weird.

                            – trante
                            Jun 29 '12 at 20:24














                          • 2





                            +1 Doh, forgot about the hover event helper! And nice suggestion about adding a class to the images - truly is a best practice :)

                            – Jarrod Dixon
                            Feb 12 '09 at 8:05






                          • 1





                            That's far better solution because it caches the old image source.

                            – trante
                            Jun 29 '12 at 20:23











                          • The negative part is, if the image is in the bottom of the page and there is 10-20 images then layout becomes weird.

                            – trante
                            Jun 29 '12 at 20:24








                          2




                          2





                          +1 Doh, forgot about the hover event helper! And nice suggestion about adding a class to the images - truly is a best practice :)

                          – Jarrod Dixon
                          Feb 12 '09 at 8:05





                          +1 Doh, forgot about the hover event helper! And nice suggestion about adding a class to the images - truly is a best practice :)

                          – Jarrod Dixon
                          Feb 12 '09 at 8:05




                          1




                          1





                          That's far better solution because it caches the old image source.

                          – trante
                          Jun 29 '12 at 20:23





                          That's far better solution because it caches the old image source.

                          – trante
                          Jun 29 '12 at 20:23













                          The negative part is, if the image is in the bottom of the page and there is 10-20 images then layout becomes weird.

                          – trante
                          Jun 29 '12 at 20:24





                          The negative part is, if the image is in the bottom of the page and there is 10-20 images then layout becomes weird.

                          – trante
                          Jun 29 '12 at 20:24











                          13














                          I was hoping for an über one liner like:



                          $("img.screenshot").attr("src", $(this).replace("foo", "bar"));





                          share|improve this answer






























                            13














                            I was hoping for an über one liner like:



                            $("img.screenshot").attr("src", $(this).replace("foo", "bar"));





                            share|improve this answer




























                              13












                              13








                              13







                              I was hoping for an über one liner like:



                              $("img.screenshot").attr("src", $(this).replace("foo", "bar"));





                              share|improve this answer















                              I was hoping for an über one liner like:



                              $("img.screenshot").attr("src", $(this).replace("foo", "bar"));






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Mar 11 '11 at 2:58









                              Jason Plank

                              2,15942739




                              2,15942739










                              answered Feb 24 '11 at 18:44









                              chovychovy

                              36.5k33161213




                              36.5k33161213























                                  6














                                  If the solution you are looking for is for an animated button, then the best you can do to improve in performance is the combination of sprites and CSS. A sprite is a huge image that contains all the images from your site (header, logo, buttons, and all decorations you have). Each image you have uses an HTTP request, and the more HTTP requests the more time it will take to load.



                                  .buttonClass {
                                  width: 25px;
                                  height: 25px;
                                  background: url(Sprite.gif) -40px -500px;
                                  }
                                  .buttonClass:hover {
                                  width: 25px;
                                  height: 25px;
                                  background: url(Sprite.gif) -40px -525px;
                                  }


                                  The 0px 0px coordinates will be the left upper corner from your sprites.



                                  But if you are developing some photo album with Ajax or something like that, then JavaScript (or any framework) is the best.



                                  Have fun!






                                  share|improve this answer






























                                    6














                                    If the solution you are looking for is for an animated button, then the best you can do to improve in performance is the combination of sprites and CSS. A sprite is a huge image that contains all the images from your site (header, logo, buttons, and all decorations you have). Each image you have uses an HTTP request, and the more HTTP requests the more time it will take to load.



                                    .buttonClass {
                                    width: 25px;
                                    height: 25px;
                                    background: url(Sprite.gif) -40px -500px;
                                    }
                                    .buttonClass:hover {
                                    width: 25px;
                                    height: 25px;
                                    background: url(Sprite.gif) -40px -525px;
                                    }


                                    The 0px 0px coordinates will be the left upper corner from your sprites.



                                    But if you are developing some photo album with Ajax or something like that, then JavaScript (or any framework) is the best.



                                    Have fun!






                                    share|improve this answer




























                                      6












                                      6








                                      6







                                      If the solution you are looking for is for an animated button, then the best you can do to improve in performance is the combination of sprites and CSS. A sprite is a huge image that contains all the images from your site (header, logo, buttons, and all decorations you have). Each image you have uses an HTTP request, and the more HTTP requests the more time it will take to load.



                                      .buttonClass {
                                      width: 25px;
                                      height: 25px;
                                      background: url(Sprite.gif) -40px -500px;
                                      }
                                      .buttonClass:hover {
                                      width: 25px;
                                      height: 25px;
                                      background: url(Sprite.gif) -40px -525px;
                                      }


                                      The 0px 0px coordinates will be the left upper corner from your sprites.



                                      But if you are developing some photo album with Ajax or something like that, then JavaScript (or any framework) is the best.



                                      Have fun!






                                      share|improve this answer















                                      If the solution you are looking for is for an animated button, then the best you can do to improve in performance is the combination of sprites and CSS. A sprite is a huge image that contains all the images from your site (header, logo, buttons, and all decorations you have). Each image you have uses an HTTP request, and the more HTTP requests the more time it will take to load.



                                      .buttonClass {
                                      width: 25px;
                                      height: 25px;
                                      background: url(Sprite.gif) -40px -500px;
                                      }
                                      .buttonClass:hover {
                                      width: 25px;
                                      height: 25px;
                                      background: url(Sprite.gif) -40px -525px;
                                      }


                                      The 0px 0px coordinates will be the left upper corner from your sprites.



                                      But if you are developing some photo album with Ajax or something like that, then JavaScript (or any framework) is the best.



                                      Have fun!







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jul 29 '13 at 19:20









                                      kevinji

                                      8,79542952




                                      8,79542952










                                      answered Feb 11 '12 at 2:50









                                      mattmatt

                                      3382721




                                      3382721























                                          4














                                          $('img').mouseover(function(){
                                          var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
                                          $(this).attr("src", newSrc);
                                          });
                                          $('img').mouseout(function(){
                                          var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
                                          $(this).attr("src", newSrc);
                                          });





                                          share|improve this answer




























                                            4














                                            $('img').mouseover(function(){
                                            var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
                                            $(this).attr("src", newSrc);
                                            });
                                            $('img').mouseout(function(){
                                            var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
                                            $(this).attr("src", newSrc);
                                            });





                                            share|improve this answer


























                                              4












                                              4








                                              4







                                              $('img').mouseover(function(){
                                              var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
                                              $(this).attr("src", newSrc);
                                              });
                                              $('img').mouseout(function(){
                                              var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
                                              $(this).attr("src", newSrc);
                                              });





                                              share|improve this answer













                                              $('img').mouseover(function(){
                                              var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
                                              $(this).attr("src", newSrc);
                                              });
                                              $('img').mouseout(function(){
                                              var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
                                              $(this).attr("src", newSrc);
                                              });






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Mar 24 '11 at 7:10









                                              iamraseciamrasec

                                              491




                                              491























                                                  4














                                                  Whilst looking for a solution some time back, I found a similar script to the below, which after some tweaking I got working for me.



                                                  It handles two images, that almost always default to "off", where the mouse is off the image (image-example_off.jpg), and the occasional "on", where for the times the mouse is hovered, the required alternative image (image-example_on.jpg) is displayed.



                                                  <script type="text/javascript">        
                                                  $(document).ready(function() {
                                                  $("img", this).hover(swapImageIn, swapImageOut);

                                                  function swapImageIn(e) {
                                                  this.src = this.src.replace("_off", "_on");
                                                  }
                                                  function swapImageOut (e) {
                                                  this.src = this.src.replace("_on", "_off");
                                                  }
                                                  });
                                                  </script>





                                                  share|improve this answer


























                                                  • I realise that the above function would execute for all images within the DOM as it is currently coded. Supplying further context would make it focus the effect to specific img elements.

                                                    – Kristopher Rout
                                                    Sep 5 '12 at 22:50
















                                                  4














                                                  Whilst looking for a solution some time back, I found a similar script to the below, which after some tweaking I got working for me.



                                                  It handles two images, that almost always default to "off", where the mouse is off the image (image-example_off.jpg), and the occasional "on", where for the times the mouse is hovered, the required alternative image (image-example_on.jpg) is displayed.



                                                  <script type="text/javascript">        
                                                  $(document).ready(function() {
                                                  $("img", this).hover(swapImageIn, swapImageOut);

                                                  function swapImageIn(e) {
                                                  this.src = this.src.replace("_off", "_on");
                                                  }
                                                  function swapImageOut (e) {
                                                  this.src = this.src.replace("_on", "_off");
                                                  }
                                                  });
                                                  </script>





                                                  share|improve this answer


























                                                  • I realise that the above function would execute for all images within the DOM as it is currently coded. Supplying further context would make it focus the effect to specific img elements.

                                                    – Kristopher Rout
                                                    Sep 5 '12 at 22:50














                                                  4












                                                  4








                                                  4







                                                  Whilst looking for a solution some time back, I found a similar script to the below, which after some tweaking I got working for me.



                                                  It handles two images, that almost always default to "off", where the mouse is off the image (image-example_off.jpg), and the occasional "on", where for the times the mouse is hovered, the required alternative image (image-example_on.jpg) is displayed.



                                                  <script type="text/javascript">        
                                                  $(document).ready(function() {
                                                  $("img", this).hover(swapImageIn, swapImageOut);

                                                  function swapImageIn(e) {
                                                  this.src = this.src.replace("_off", "_on");
                                                  }
                                                  function swapImageOut (e) {
                                                  this.src = this.src.replace("_on", "_off");
                                                  }
                                                  });
                                                  </script>





                                                  share|improve this answer















                                                  Whilst looking for a solution some time back, I found a similar script to the below, which after some tweaking I got working for me.



                                                  It handles two images, that almost always default to "off", where the mouse is off the image (image-example_off.jpg), and the occasional "on", where for the times the mouse is hovered, the required alternative image (image-example_on.jpg) is displayed.



                                                  <script type="text/javascript">        
                                                  $(document).ready(function() {
                                                  $("img", this).hover(swapImageIn, swapImageOut);

                                                  function swapImageIn(e) {
                                                  this.src = this.src.replace("_off", "_on");
                                                  }
                                                  function swapImageOut (e) {
                                                  this.src = this.src.replace("_on", "_off");
                                                  }
                                                  });
                                                  </script>






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited Jul 29 '13 at 21:30









                                                  Peter Mortensen

                                                  13.9k1987113




                                                  13.9k1987113










                                                  answered Sep 5 '12 at 22:34









                                                  Kristopher RoutKristopher Rout

                                                  413




                                                  413













                                                  • I realise that the above function would execute for all images within the DOM as it is currently coded. Supplying further context would make it focus the effect to specific img elements.

                                                    – Kristopher Rout
                                                    Sep 5 '12 at 22:50



















                                                  • I realise that the above function would execute for all images within the DOM as it is currently coded. Supplying further context would make it focus the effect to specific img elements.

                                                    – Kristopher Rout
                                                    Sep 5 '12 at 22:50

















                                                  I realise that the above function would execute for all images within the DOM as it is currently coded. Supplying further context would make it focus the effect to specific img elements.

                                                  – Kristopher Rout
                                                  Sep 5 '12 at 22:50





                                                  I realise that the above function would execute for all images within the DOM as it is currently coded. Supplying further context would make it focus the effect to specific img elements.

                                                  – Kristopher Rout
                                                  Sep 5 '12 at 22:50











                                                  3














                                                  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                                                  <html xmlns="http://www.w3.org/1999/xhtml">
                                                  <head>
                                                  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
                                                  <title>JQuery</title>
                                                  <script src="jquery.js" type="text/javascript"> </script>
                                                  <style type="text/css">
                                                  #box{
                                                  width: 68px;
                                                  height: 27px;
                                                  background: url(images/home1.gif);
                                                  cursor: pointer;
                                                  }
                                                  </style>

                                                  <script type="text/javascript">

                                                  $(function(){

                                                  $('#box').hover( function(){
                                                  $('#box').css('background', 'url(images/home2.gif)');

                                                  });
                                                  $('#box').mouseout( function(){
                                                  $('#box').css('background', 'url(images/home1.gif)');

                                                  });

                                                  });
                                                  </script>
                                                  </head>

                                                  <body>
                                                  <div id="box" onclick="location.href='index.php';"></div>
                                                  </body>
                                                  </html>





                                                  share|improve this answer






























                                                    3














                                                    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                                                    <html xmlns="http://www.w3.org/1999/xhtml">
                                                    <head>
                                                    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
                                                    <title>JQuery</title>
                                                    <script src="jquery.js" type="text/javascript"> </script>
                                                    <style type="text/css">
                                                    #box{
                                                    width: 68px;
                                                    height: 27px;
                                                    background: url(images/home1.gif);
                                                    cursor: pointer;
                                                    }
                                                    </style>

                                                    <script type="text/javascript">

                                                    $(function(){

                                                    $('#box').hover( function(){
                                                    $('#box').css('background', 'url(images/home2.gif)');

                                                    });
                                                    $('#box').mouseout( function(){
                                                    $('#box').css('background', 'url(images/home1.gif)');

                                                    });

                                                    });
                                                    </script>
                                                    </head>

                                                    <body>
                                                    <div id="box" onclick="location.href='index.php';"></div>
                                                    </body>
                                                    </html>





                                                    share|improve this answer




























                                                      3












                                                      3








                                                      3







                                                      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                                                      <html xmlns="http://www.w3.org/1999/xhtml">
                                                      <head>
                                                      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
                                                      <title>JQuery</title>
                                                      <script src="jquery.js" type="text/javascript"> </script>
                                                      <style type="text/css">
                                                      #box{
                                                      width: 68px;
                                                      height: 27px;
                                                      background: url(images/home1.gif);
                                                      cursor: pointer;
                                                      }
                                                      </style>

                                                      <script type="text/javascript">

                                                      $(function(){

                                                      $('#box').hover( function(){
                                                      $('#box').css('background', 'url(images/home2.gif)');

                                                      });
                                                      $('#box').mouseout( function(){
                                                      $('#box').css('background', 'url(images/home1.gif)');

                                                      });

                                                      });
                                                      </script>
                                                      </head>

                                                      <body>
                                                      <div id="box" onclick="location.href='index.php';"></div>
                                                      </body>
                                                      </html>





                                                      share|improve this answer















                                                      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
                                                      <html xmlns="http://www.w3.org/1999/xhtml">
                                                      <head>
                                                      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
                                                      <title>JQuery</title>
                                                      <script src="jquery.js" type="text/javascript"> </script>
                                                      <style type="text/css">
                                                      #box{
                                                      width: 68px;
                                                      height: 27px;
                                                      background: url(images/home1.gif);
                                                      cursor: pointer;
                                                      }
                                                      </style>

                                                      <script type="text/javascript">

                                                      $(function(){

                                                      $('#box').hover( function(){
                                                      $('#box').css('background', 'url(images/home2.gif)');

                                                      });
                                                      $('#box').mouseout( function(){
                                                      $('#box').css('background', 'url(images/home1.gif)');

                                                      });

                                                      });
                                                      </script>
                                                      </head>

                                                      <body>
                                                      <div id="box" onclick="location.href='index.php';"></div>
                                                      </body>
                                                      </html>






                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Mar 13 '10 at 16:14









                                                      Imran

                                                      45.2k2085117




                                                      45.2k2085117










                                                      answered May 23 '09 at 7:10







                                                      faruque






























                                                          2














                                                          I've made something like the following code :)



                                                          It works only, when you have a second file named with _hover, for example, facebook.png and facebook_hover.png



                                                          $('#social').find('a').hover(function() {
                                                          var target = $(this).find('img').attr('src');
                                                          //console.log(target);
                                                          var newTarg = target.replace('.png', '_hover.png');
                                                          $(this).find('img').attr("src", newTarg);
                                                          }, function() {
                                                          var target = $(this).find('img').attr('src');
                                                          var newTarg = target.replace('_hover.png', '.png');
                                                          $(this).find('img').attr("src", newTarg);
                                                          });





                                                          share|improve this answer






























                                                            2














                                                            I've made something like the following code :)



                                                            It works only, when you have a second file named with _hover, for example, facebook.png and facebook_hover.png



                                                            $('#social').find('a').hover(function() {
                                                            var target = $(this).find('img').attr('src');
                                                            //console.log(target);
                                                            var newTarg = target.replace('.png', '_hover.png');
                                                            $(this).find('img').attr("src", newTarg);
                                                            }, function() {
                                                            var target = $(this).find('img').attr('src');
                                                            var newTarg = target.replace('_hover.png', '.png');
                                                            $(this).find('img').attr("src", newTarg);
                                                            });





                                                            share|improve this answer




























                                                              2












                                                              2








                                                              2







                                                              I've made something like the following code :)



                                                              It works only, when you have a second file named with _hover, for example, facebook.png and facebook_hover.png



                                                              $('#social').find('a').hover(function() {
                                                              var target = $(this).find('img').attr('src');
                                                              //console.log(target);
                                                              var newTarg = target.replace('.png', '_hover.png');
                                                              $(this).find('img').attr("src", newTarg);
                                                              }, function() {
                                                              var target = $(this).find('img').attr('src');
                                                              var newTarg = target.replace('_hover.png', '.png');
                                                              $(this).find('img').attr("src", newTarg);
                                                              });





                                                              share|improve this answer















                                                              I've made something like the following code :)



                                                              It works only, when you have a second file named with _hover, for example, facebook.png and facebook_hover.png



                                                              $('#social').find('a').hover(function() {
                                                              var target = $(this).find('img').attr('src');
                                                              //console.log(target);
                                                              var newTarg = target.replace('.png', '_hover.png');
                                                              $(this).find('img').attr("src", newTarg);
                                                              }, function() {
                                                              var target = $(this).find('img').attr('src');
                                                              var newTarg = target.replace('_hover.png', '.png');
                                                              $(this).find('img').attr("src", newTarg);
                                                              });






                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Jul 29 '13 at 21:28









                                                              Peter Mortensen

                                                              13.9k1987113




                                                              13.9k1987113










                                                              answered Feb 14 '13 at 14:06









                                                              GrzegorzGrzegorz

                                                              211




                                                              211























                                                                  1














                                                                  <img src="img1.jpg" data-swap="img2.jpg"/>



                                                                  img = {

                                                                  init: function() {
                                                                  $('img').on('mouseover', img.swap);
                                                                  $('img').on('mouseover', img.swap);
                                                                  },

                                                                  swap: function() {
                                                                  var tmp = $(this).data('swap');
                                                                  $(this).attr('data-swap', $(this).attr('src'));
                                                                  $(this).attr('str', tmp);
                                                                  }
                                                                  }

                                                                  img.init();





                                                                  share|improve this answer




























                                                                    1














                                                                    <img src="img1.jpg" data-swap="img2.jpg"/>



                                                                    img = {

                                                                    init: function() {
                                                                    $('img').on('mouseover', img.swap);
                                                                    $('img').on('mouseover', img.swap);
                                                                    },

                                                                    swap: function() {
                                                                    var tmp = $(this).data('swap');
                                                                    $(this).attr('data-swap', $(this).attr('src'));
                                                                    $(this).attr('str', tmp);
                                                                    }
                                                                    }

                                                                    img.init();





                                                                    share|improve this answer


























                                                                      1












                                                                      1








                                                                      1







                                                                      <img src="img1.jpg" data-swap="img2.jpg"/>



                                                                      img = {

                                                                      init: function() {
                                                                      $('img').on('mouseover', img.swap);
                                                                      $('img').on('mouseover', img.swap);
                                                                      },

                                                                      swap: function() {
                                                                      var tmp = $(this).data('swap');
                                                                      $(this).attr('data-swap', $(this).attr('src'));
                                                                      $(this).attr('str', tmp);
                                                                      }
                                                                      }

                                                                      img.init();





                                                                      share|improve this answer













                                                                      <img src="img1.jpg" data-swap="img2.jpg"/>



                                                                      img = {

                                                                      init: function() {
                                                                      $('img').on('mouseover', img.swap);
                                                                      $('img').on('mouseover', img.swap);
                                                                      },

                                                                      swap: function() {
                                                                      var tmp = $(this).data('swap');
                                                                      $(this).attr('data-swap', $(this).attr('src'));
                                                                      $(this).attr('str', tmp);
                                                                      }
                                                                      }

                                                                      img.init();






                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Apr 15 '12 at 17:39









                                                                      Gustav WestlingGustav Westling

                                                                      62536




                                                                      62536























                                                                          1














                                                                          Adapted from Richard Ayotte's code -
                                                                          To target an img in a ul/li list (found via wrapper div class here), something like this:



                                                                          $('div.navlist li').bind('mouseenter mouseleave', function() {    
                                                                          $(this).find('img').attr({ src: $(this).find('img').attr('data-alt-src'),
                                                                          'data-alt-src':$(this).find('img').attr('src') }
                                                                          );





                                                                          share|improve this answer




























                                                                            1














                                                                            Adapted from Richard Ayotte's code -
                                                                            To target an img in a ul/li list (found via wrapper div class here), something like this:



                                                                            $('div.navlist li').bind('mouseenter mouseleave', function() {    
                                                                            $(this).find('img').attr({ src: $(this).find('img').attr('data-alt-src'),
                                                                            'data-alt-src':$(this).find('img').attr('src') }
                                                                            );





                                                                            share|improve this answer


























                                                                              1












                                                                              1








                                                                              1







                                                                              Adapted from Richard Ayotte's code -
                                                                              To target an img in a ul/li list (found via wrapper div class here), something like this:



                                                                              $('div.navlist li').bind('mouseenter mouseleave', function() {    
                                                                              $(this).find('img').attr({ src: $(this).find('img').attr('data-alt-src'),
                                                                              'data-alt-src':$(this).find('img').attr('src') }
                                                                              );





                                                                              share|improve this answer













                                                                              Adapted from Richard Ayotte's code -
                                                                              To target an img in a ul/li list (found via wrapper div class here), something like this:



                                                                              $('div.navlist li').bind('mouseenter mouseleave', function() {    
                                                                              $(this).find('img').attr({ src: $(this).find('img').attr('data-alt-src'),
                                                                              'data-alt-src':$(this).find('img').attr('src') }
                                                                              );






                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Jul 15 '16 at 14:29









                                                                              anoldermarkanoldermark

                                                                              19317




                                                                              19317






























                                                                                  draft saved

                                                                                  draft discarded




















































                                                                                  Thanks for contributing an answer to Stack Overflow!


                                                                                  • Please be sure to answer the question. Provide details and share your research!

                                                                                  But avoid



                                                                                  • Asking for help, clarification, or responding to other answers.

                                                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                                                  To learn more, see our tips on writing great answers.




                                                                                  draft saved


                                                                                  draft discarded














                                                                                  StackExchange.ready(
                                                                                  function () {
                                                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f540349%2fchange-the-image-source-on-rollover-using-jquery%23new-answer', 'question_page');
                                                                                  }
                                                                                  );

                                                                                  Post as a guest















                                                                                  Required, but never shown





















































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown

































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown







                                                                                  Popular posts from this blog

                                                                                  Mossoró

                                                                                  Error while reading .h5 file using the rhdf5 package in R

                                                                                  Pushsharp Apns notification error: 'InvalidToken'