Obsivus
Obsivus

Reputation: 8359

Swap back image on hover out with Jquery

I have this HTML code:

<a href="#"><img class="swap" src="/Static/Images/Meny_normal_01.png"  alt="" /></a>

and this is my Jquery code and what it does is that when I hover over my img it swaps to another img, but I would like to have a hover out and then it swap back to the old img.

$(document).ready(function () {
    $('.swap').hover(function () {
        $(this).attr('src', '/Static/Images/Meny_hover_01.png');
    });
});

Would appreciate any kind of help

Upvotes: 1

Views: 955

Answers (3)

Eli
Eli

Reputation: 14827

.hover() binds two handlers to the matched elements, to be executed when the mouse pointer enters and when you leaves the elements.

$(".swap").hover(
  function () {
    $(this).attr('src', '/Static/Images/Meny_hover_01.png');
  },
  function () {
    $(this).attr('src', '/Static/Images/Meny_normal_01.png');
  }
);

Upvotes: 3

VisioN
VisioN

Reputation: 145398

$(".swap").hover(function() {
    $(this).attr("src", function(i, val) {
        return val.indexOf("hover") == -1
          ? val.replace("normal", "hover")
          : val.replace("hover", "normal");
    });
});

DEMO: http://jsfiddle.net/UJR8M/

Upvotes: 0

geedubb
geedubb

Reputation: 4057

You can pass 2 handlers into the hover - like this:

$(document).ready(function () {
    $('.swap').hover(function () {
        $(this).attr('src', '/Static/Images/Meny_hover_01.png');
    },
    function () {
        $(this).attr('src', '/Static/Images/Meny_normal_01.png');
    }
    );
});

Have a look at: http://api.jquery.com/hover/ for more info

Or a similar item on SO: jquery change image on mouse rollover

Upvotes: 1

Related Questions