Satch3000
Satch3000

Reputation: 49404

Jquery Onmouseover change img attr with effect

I am using jquery onmouseover to change the src of an image like this:

$( ".myimage" ).mouseover(function() {

   $('.myimage').attr('src', 'imageHover.png');

});

My question is... How do I add a transition effect to the code above?

Upvotes: 1

Views: 839

Answers (2)

Nageshwar Reddy
Nageshwar Reddy

Reputation: 32

you can give the fade effects like this

$("#image").hover(function() {
    $("#image").fadeOut(1000, function() {
        $("#image").attr("src",$("#image").data("first"));
    }).fadeIn(1000);
    return false;
},function() {
    $("#image").fadeOut(1000, function() {
        $("#image").attr("src",$("#image").data("second"));
    }).fadeIn(1000);
    return false;
});

Working example is here

Upvotes: 1

Itay
Itay

Reputation: 16785

There's no CSS (<=3) transition for the src attribute. You'll have to add another img element and use some kind of a custom transition with jQuery (like .fadeOut)

Look at these threads for instance:

Animating "src" attribute

JQuery Switch Img Src with fade effect


If you need the effect to work when the image is hovered, like you showed in your post, you can do it with only CSS using two different images.

By default, show only the regular image. When the container is hover, hide the first one with opacity: 0 and its CSS transition, and show the other one.

Working jsFiddle

div {
    position: relative;
}
img {
    position: absolute;
    transition: opacity 0.5s linear;
}
#b {
    opacity: 0;
}
div:hover #b {
    opacity: 1;
}
div:hover #a {
    opacity: 0;
}

Upvotes: 1

Related Questions