Cameron
Cameron

Reputation: 28853

jQuery show/hide element when hovering another element

I have the following HTML as an example:

<div id="header">
<div class="pagination"></div>
</div>

and the following jQuery which should hide the pagination by default but then fade it in when a user hovers the header and then fades it back out when they move off the header:

            $(".pagination").hide();
            $("#header").mousemove(function()
            {
                $(".pagination").fadeIn(1500);
            });
            $("#header").mouseleave(function()
            {
                $(".pagination").fadeOut(1500);
            });

The problem I have is that it will run through the code the same number of times a user hovers the header so for example if I hovered 5 times in a row the pagination would fade in and out 5 times. This is not the function I want, rather a simple fade in and out when a user is hovering the header.

Can anyone help? Thanks.

Upvotes: 2

Views: 1283

Answers (2)

Vincent Ramdhanie
Vincent Ramdhanie

Reputation: 103145

Edited: Added some code to avoid repeated fading in and out.

     var running = false;

     $("#header").hover(function()
        {
            if(!running){
               $(".pagination").fadeIn(1500);
               running = true;
            }
        }, function()
        {
            $(".pagination").fadeOut(1500, function(){
                running = false;
            });
        });

Now, the hover effect only kicks in if it is not already running.

Upvotes: 4

Roko C. Buljan
Roko C. Buljan

Reputation: 206618

well than instead of fadeIn - fadeOut just use .fadeTo like in my

JSFiddle DEMO

And to stop the issue you are talking about use .stop()

Good Luck!

Upvotes: 2

Related Questions