Search code examples
jquerymouseentermouseleave

Mouseleave doesn't trigger when Mouseenter is not completed yet


I'm having a problem with mouseenter and mouseleave with jquery.

When entering a div, the mouseenter function will start. When I leave the div before the mouseenter is completed, the mouseleave wont trigger.

I have made a jsfiddle to make it easier to understand.

http://jsfiddle.net/8sLLD/1/

code:

$("#menu1").mouseenter(function() {
   //code

})
    $("#image").mouseleave(function () {
    //code
});

So, when entering the button, an image appears. When you leave the button before the image has appeared (before your cursor touches the image) the mouseleave won't trigger.

EDIT: When using #menu for the mouseleave, the image will act very weird when just "moving" the mouse.

I know there are already some questions like this, but none of them worked for me.

Thanks a lot and sorry for my english


Solution

  • You can use a hover event handler to set your in and out handler function.

    Is more simple if you set your hover on a wrapping element like #p2, so it will be fired when you enter/exit the wrapper not its children.

    Code:

     $('document').ready(function () {
         $("#p2").hover(function () {
             $(this).css("cursor", "pointer")
    
             $("#image").css("left", "75");
             $("#image").stop().animate({
                 width: "145px",
                 height: "145px",
                 left: "0"
             }, 'slow');
    
             $("#c").animate({
                 top: "100"
             }, 'slow');
    
         }, function () {
             $("#image").stop().animate({
                 width: "0%",
                 height: "0%",
                 left: "75"
             }, 'slow');
             $("#c").animate({
                 top: "0"
             }, 'slow');
         });
     });
    

    Demo: http://jsfiddle.net/qwPvv/