0

I'm trying to show an overlay div when '.menu' is hovered over. I've used hover to show the div (hidden first with CSS), the mouseleave to reset it. How can I do it so the mouse needs to be on the menu for a couple of seconds for it to show, so if its just rolled over quickly it doesnt do anything. I know I can do this with delay() but if i go over the button quickly 5 times, the screen flashes 5 times with the overlay. How can i make it only do it once and then terminate.

Thanks.

 $( document ).ready(function() {

        $(".menu").hover(function() {
            $(".page-overlay").delay(600).fadeIn(200);
        });

        $(".menu").mouseleave(function() { 
            $(".page-overlay").fadeOut(200); 
        });

});
Nick Zuber
  • 5,467
  • 3
  • 24
  • 48
jord49
  • 542
  • 2
  • 17
  • 37
  • Possible duplicate of [Delay jquery hover event?](http://stackoverflow.com/questions/435732/delay-jquery-hover-event) – Linus Thiel Dec 08 '15 at 19:26
  • I voted to close this as a duplicate of http://stackoverflow.com/questions/435732/delay-jquery-hover-event -- I think the advice is good; while it's possible to solve this with `setTimeout`/`clearTimeout`, it can be hard to get it right and people seem happy with the hoverIntent plugin. – Linus Thiel Dec 08 '15 at 19:27
  • @LinusGustavLarssonThiel shouldn't all answers to questions be void of recommendations from third party software? – johnny 5 Dec 08 '15 at 19:37

2 Answers2

1

You can use setTimeout and clearTimeout, check example bellow.

I can do this with delay() but if i go over the button quickly 5 times, the screen flashes 5 times with the overlay

Using the clearTimeout() function in hoverOut() in example bellow will resolve this problem.

Hope this helps.


$( document ).ready(function() {
    var menu_hover_timer;
    $(".page-overlay").hide();

    $( ".menu" ).hover(
        function() {
            menu_hover_timer = setTimeout(function(){
                $(".page-overlay").fadeIn(200);
            },1000); //wait 1 seconds
        }, function() {
            clearTimeout(menu_hover_timer)
        }
    );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='menu'>
  Menu (Stay hover 1 second HERE)
</div>
<div class='page-overlay'>
  page overlay div
</div>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

jQuery's hover method accommodates for the mouse entering and leaving events, so you don't really need to make an explicit mouseleave event handler.

hover works like this:

$( ... ).hover(function(){
    // Here is the mouse entering function
},
function(){
    // Here is the mouse exiting function
});

So you can adjust your code to something like this:

$(".menu").hover(function() {
    $(".page-overlay").delay(600).fadeIn(200);
},
function(){
    $(".page-overlay").fadeOut(200);
});
Nick Zuber
  • 5,467
  • 3
  • 24
  • 48