Search code examples
javascriptjqueryevent-handlinglistenerdom-events

How to execute a function only if a mouseover listener is not active


In order to avoid a sort of flickering effect on the screen due to rollover effects on my page, I want to activate a function from mouseOut of a thumbnail only if a mouseOver state on a different thumbnail is not currently happening. How would I do this?


Solution

  • You can check to see if any your thumbnail elements have an active class that is added when a successful mouseout event fires. If any other thumbnail elements have this class then do nothing, if none are found then run your mouseout code:

    $('.thumb-element').on('mouseout', function () {
        if ($('.thumb-element').filter('.active-mouseout').length == 0) {
            //there are no elements with both the `thumb-element` class and the `active-mouseout` class so you can do work here
            $(this).addClass('active-mouseout').animate({top : 'XXpx'}, 250, function () {
    
                //now we remove the `active-mouseout` class so another `mouseout` event can run
                $(this).removeClass('active-mouseout');
            });
        }
    });
    

    You can then remove the active-mouseout class when necessary, for instance if it requires an animation then you can remove this class in the callback for that animation.

    Here is a jsfiddle of the above solution: http://jsfiddle.net/jasper/zg5g7/