Question

I have two images. One is of a particular location from a while ago, the other is the same location today. I want the images to swap when you mouse over one of them.

My HTML looks like this:

<div id="popup" class="rounded-corners">
    <div class='close'></div>
    <h3>my title</h3>
    <img id="img_then" src="./images/path1.jpg" />
    <img id="img_now" src="./images/path2.jpg" />
</div>

The jQuery code looks like this:

$("#popup img").one("mouseenter", function() {  
    if ($('#img_now').is(":visible")) {
        $('#img_then').fadeIn(2000);
        $("#img_now").fadeOut(2000);
    }
    else if ($('#img_then').is(":visible")) {
        $('#img_then').fadeOut(2000);
        $("#img_now").fadeIn(2000);
    }
});

But what happens is that on mouse over, the image switches from old to new, then from new to old. I've tried a number of permutations, including the addition of "return false;" but nothing seems to be working. Anyone have any advice, please?

Was it helpful?

Solution

I'd suggest binding the 'mouseenter' handler on the '#popup' element alone.

Or add a wrapper around the images, and target this wrapper :

   <div id="images">
      <img id="img_then" ...>
      <img id="img_now" ...>
   </div>

$("#images").on("mouseenter", function(){
  if ($("#img_now").is(":visible")) {
    $("#img_then").fadeIn(2000);
    $("#img_now").fadeOut(2000);
  }
  else if ($("#img_then").is(":visible")) {
    $("#img_then").fadeOut(2000);
    $("#img_now").fadeIn(2000);
  }
});

OTHER TIPS

Do this bind it to the one visible otherwise you bind it to both images

$( "#popup img:visible" ).one( "mouseenter", function() {  

DEMO

The duration for fadeIn/fadeOut is two seconds. Could the issue be that you get a new mouseenter event while the fade is still in progress? I think your if condition about element being visible will only be true when the fade is finished.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top