jord49
jord49

Reputation: 582

How can I control my hover event in jQuery?

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); 
        });

});

Upvotes: 0

Views: 137

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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>

Upvotes: 1

Nick Zuber
Nick Zuber

Reputation: 5637

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);
});

Upvotes: 1

Related Questions