carcargi
carcargi

Reputation: 505

Jquery mouseleave autofires on IE

I have a problem with this code, the mouseleave function is firing on IE without the mouse entering first in the div.

<script type="text/javascript">
$(document).ready(function() {
    $('#<?php echo 'div_'.$reload_cont; ?>').mouseenter(function() {

        var el = $(this);
        var timeoutId = setTimeout(function() {
            $('#<?php echo 'relo_'.$reload_cont; ?>').animate({opacity: 1}, 'slow');
        }, 500);

        el.mouseleave(function() {
            clearTimeout(timeoutId);
            $('#<?php echo 'relo_'.$reload_cont; ?>').animate({opacity: 0}, 'slow');
        });
    });
});

</script>

I've tryied a lot of ways and none seems to work.

Any help here

Upvotes: 1

Views: 352

Answers (1)

Jasper
Jasper

Reputation: 76003

You are re-binding the mouseleave event every-time the mouseenter event fires, try moving the mouseleave event handler outside the mouseenter event handler:

$(function() {

    //notice the timeout variable is saved in a scope where both event handlers can access it
    var timeoutId;

    $('#<?php echo 'div_'.$reload_cont; ?>').mouseenter(function() {

        timeoutId = setTimeout(function() {
            $('#<?php echo 'relo_'.$reload_cont; ?>').stop().animate({opacity: 1}, 'slow');
        }, 500);
    }).mouseleave(function() {
        clearTimeout(timeoutId);
        $('#<?php echo 'relo_'.$reload_cont; ?>').stop().animate({opacity: 0}, 'slow');
    });
});

Notice the use of .stop() so multiple animations don't queue-up if you mouse-enter and then mouse-leave many times rapidly.

Here is a demo: http://jsfiddle.net/jasper/LJAqd/

I tested this in IE 8/7 and it worked as expected, but I can't be sure it will work for your implementation because I don't know the HTML structure of your code.

Upvotes: 2

Related Questions