Search code examples
jquerymouseovermouseenter

want something to happen once on mouseenter, but happening twice


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?


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);
      }
    });