0

I'm trying to get an image to fade out on hover, swap the image src, then fade back in. I'm animating opacity as the fadein/out functions set the element to display:none and I don't want this to happen.

Here's my code:

$('.imgswap').on({
'mouseenter': function(){
    var $nextimg = $(this).data('imagesource');
        if ($nextimg != $('#floorplan').attr('src')) {
        $('#floorplan').animate({"opacity": "0"}, "fast",function () {
            $('#floorplan').attr('src',$nextimg).animate({"opacity": "1"}, "fast");
        });
    }
}
});

Can you see why the second animate function is not firing off AFTER setting the source?

UPDATE: After further testing, and trying one of the comments below, it turns out that the animate IS firing after the SRC has been set, but if the new image hasn't loaded in yet, the old image stays visible until the new one is available. So... I think I need some sort of 'loader' that only fires the animate({"opacity": "1"}, "fast") when the new image has been loaded in.

Mere Development
  • 2,439
  • 5
  • 32
  • 63

1 Answers1

1

Here is the DOM I used with the JS above and it works great:

<div class="imgswap" data-imagesource="http://placehold.it/350x450">
  <img id="floorplan" src="http://placehold.it/350x150"/>
</div>

CodePen: http://codepen.io/anon/pen/CGKaF

To address your loading concerns, I've updated the codepen to look to see if it's loaded. Try that out. Also, check out jQuery callback on image load (even when the image is cached) and this handy plugin: https://github.com/desandro/imagesloaded

Community
  • 1
  • 1
Lost Left Stack
  • 1,932
  • 13
  • 14
  • Hi, thanks, I see the same thing with this example. I've realised that it's because I have cache disabled (during development, always do) and the image is having to load in each time. I will modify the question to reflect this. Thanks for the help so far. – Mere Development Sep 04 '13 at 07:59
  • I LOVE that .on() function. Just using .load() results in loads of things firing off on each retry. Thanks loads! Perfect. – Mere Development Sep 05 '13 at 10:36