Image swap jquery mouseover

Ben Thompson picture Ben Thompson · Jan 7, 2013 · Viewed 14.2k times · Source

I am currently having some problems getting a mouseover and mouseout function to work in jquery. I have two images called 'images/doomsday.jpg' and the other called 'keep_calm.png' which i want to swap when the mouse is over them and then swap back when it is not. I have included the code I am currently trying to use, can anybody see any problems with it and where I am going wrong?

$(function() {
$("images/doomsday.jpg")
    .mouseover(function() { 
        var src = $(this).attr("src").match(/[^\.]+/) + "images/keep_calm.png";
        $(this).attr("src", src);
    })
    .mouseout(function() {
        var src = $(this).attr("src").replace("images/keep_calm.png");
        $(this).attr("src", src);
    });

});

Answer

Pranav 웃 picture Pranav 웃 · Jan 7, 2013

Your selectors are wrong. You can learn about the selectors here.

Here is a demo of image swapping.

Code :

$('document').ready(function() {

  $('img').on({
    'mouseover' : function() {
      $(this).attr('src','http://media02.hongkiat.com/css3-code-slim/css3-markup.jpg');
    },
    mouseout : function() {
  $(this).attr('src','http://www.w3.org/html/logo/downloads/HTML5_Logo_512.png');
    }
  });
});