jQuery mouseenter() and mouseleave() functions work repeatedly

33,003

Solution 1

I found the solution. When I changed the element that works with the mouseleave event, it worked:

var block = false;
$("#pic").mouseenter(function(){
if(!block) {
    block = true;
    $("#toggleDiv").slideDown(400, function(){
        block = false;
    });
}
});
$("#pic").mouseleave(function(){
if(!block) {
    block = true;
    $("#toggleDiv").slideUp(400, function(){
        block = false;
    });
}
});

Thank you for your help.

Update: I noticed that giving both the picture and div a class and defining the mouseenter and mouseleave events of the class is a better solution.

Solution 2

May fix something like this:

var block = false;
$("#pic").mouseenter(function(){
    if(!block) {
        block = true;
        $("#toggleDiv").slideDown(400, function(){
            block = false;
        });
    }
});
$("#pic").mouseleave(function(){
    if(!block) {
        block = true;
        $("#toggleDiv").slideUp(400, function(){
            block = false;
        });
    }
});

http://jsfiddle.net/BnPJ4/

Share:
33,003
Baris Demirel
Author by

Baris Demirel

Updated on July 02, 2020

Comments

  • Baris Demirel
    Baris Demirel almost 4 years

    I have a picture and a div. The div is hidden(display:none;). I want to show the div when mouse is over the picture and hide the div again when mouse is not over the picture. I use mouseenter() and mouseleave() events to do this but when moue is over the picture, both of the functions work repeatedly. Here is the code that I define functions:`

    $("#pic").mouseenter(function(){
      $("#checkin").slideDown();
    });
    $("#pic").mouseleave(function(){
      $("#checkin").slideUp();
    });
    

    I also tried the hover method but the result is the same.

    $("#pic").hover(
      function(){
        $("#checkin").slideDown(200);
      },
      function(){
        $("#checkin").slideUp(200);
      }
    );
    

    What is the problem, I can't understand.

    Update: Here is the HTML code

    <tr><td valign='top' class='checkinpic'><img src='img.png' id='pic' height='100%'></td></tr>
    

    ...

    <div id='checkin'>
    You are not going to any activity this week.
    </div>
    
  • Baris Demirel
    Baris Demirel about 10 years
    Yes, it solved the repetition problem, but now, mouseleave function does not work. So it works for one time, until the div is shown.
  • Baris Demirel
    Baris Demirel about 10 years
    The same problem continues, I want the div to show over the picture, that's why it repeats.