Search code examples
jquerymouseeventdelayjquery-events

Repeating event and how to avoid


My jQuery code is:

$(document).ready(function () {
    $('.selector').mouseenter(function () {
        $(this).find('> ul').slideToggle('fast');
    });
    $('.selector').mouseleave(function () {
        $(this).find('> ul').slideToggle('fast');
    });
});

In work at:

http://jsfiddle.net/Reuben/Au7LA/1/

My code works, but if your not careful you can make a rapid attack of opening an closing panels. So is there a delay or rather what can someone do to prevent this from occurring?


Solution

  • $(document).ready(function () {
        $('.selector').mouseenter(function () {
            $(this).find('> ul').stop().slideToggle('fast');
        });
        $('.selector').mouseleave(function () {
            $(this).find('> ul').stop().slideToggle('fast');
        });
    });
    

    http://jsfiddle.net/Au7LA/3

    Also probably debouncing plugin will be useful for you http://benalman.com/code/projects/jquery-throttle-debounce/docs/files/jquery-ba-throttle-debounce-js.html


    UPDATE (Using debounce):

    $(document).ready(function () {
        var toggle = function (show) {
            return function () {
                var $el = $(this);
                var isHovered = $el.is(':hover');
                var animation = show && isHovered ? 'slideDown' : 'slideUp';
                $el.children('ul').stop()[animation]('fast');
            };
        }
        var mouseenter = $.debounce(400, toggle(true));
        var mouseleave = toggle(false);
        $('.selector')
            .on('mouseenter', mouseenter)
            .on('mouseleave', mouseleave);
    });
    

    http://jsfiddle.net/vpetrychuk/4C6CV/