vonholmes
vonholmes

Reputation: 61

Simple image swap with fade on hover

I'm looking for a simple way to swap an image on hover with cross fade. I have seen lots of solutions - but everything I have found seems bloated & complicated. Is there a simple way to achieve this?

Img swap code I'm using:

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

Is there a way to add fadeIn / fadeOut here? Or is this the wrong way to go about this? Everything I've tried doesn't seem to work! Any help would be greatly appreciated.

Upvotes: 2

Views: 8919

Answers (3)

adeneo
adeneo

Reputation: 318322

To cross fade two images, both images will at some point be visible, so you'll need two images in the DOM. You could do it with just one image, but then you would have to fade the image out, swap the source, and fade it in, which is'nt really a cross fade.

<img src="image1.png" id="test" />
<img src="image2.png" id="test2" />​

JS:

$('#test').on('mouseenter', function() {
        $(this).fadeOut('slow');
        $('#test2').fadeIn('slow');
});

$('#test2').css({left: $('#test').position().left, top: $('#test').position().top})
           .on('mouseleave', function() {
        $(this).fadeOut('slow');
        $('#test').fadeIn('slow');
});
​

FIDDLE

Upvotes: 2

Praveen kalal
Praveen kalal

Reputation: 2129

use below code and also include the jquery.

 $("#one").hover(function(){$('#one').fadeOut(1000);$('#two').fadeIn(2000);}
);
 $('#one').fadeIn(2000);

<span id="one"><img serc="image1path"></span>
<span id="two" style="display:none"><img serc="image2path"></span>

Upvotes: 0

Roko C. Buljan
Roko C. Buljan

Reputation: 206505

jsBin demo

  $(".img-swap").on('mouseenter mouseleave', function( e ){

    var mE = e.type=='mouseenter';
    var c = ['_on','_off'];
    this.src = this.src.replace( mE?c[1]:c[0] , mE?c[0]:c[1] );
    $(this).hide().stop().fadeTo(1000,1);

  });

Upvotes: 2

Related Questions