DanC
DanC

Reputation: 1307

Jquery delayed css div position

I am trying to make my menu bar partially hide after a timeout of about 5 seconds of inactivity. The menu is positioned 20px from the top of the page and the basic idea is that a small section of the menu will still be visible once it has moved up to allow the user to hover over this for it to drop down again (hopefully this makes sense!).

I have managed the animation side but not quite the timeout. Any ideas?

Upvotes: 1

Views: 1707

Answers (4)

Antony Carthy
Antony Carthy

Reputation: 5597

On the mouseout event start a timeout with the callback to scroll the element up. On the mousover event, if there is a timeout, kill it using:

clearTimeout(timer); 

So it will be something like:

var timer;
$('mybar').mouseover(function(){clearTimeout(timer);/* Animate down code here */});
$('mybar').mouseout(function(){timer=setTimeout(function(){/* Animate up Code Here */}, 5000);});

Upvotes: 1

Ronald Wildenberg
Ronald Wildenberg

Reputation: 32104

You should use the mouseout event of the div that represents the menu to implement a function like this:

var waitingForMenuToHide = false;

function myOnMouseOut() {
    waitingForMenuToHide = true;
    setTimeout(function() {
        if (waitingForMenuToHide) {
            // Hide the menu div...
        }
    }, 5000);
}

and the mouseover event to reset the waitingForMenuToHide variable:

function myMouseOver() {
    waitingForMenuToHide = false;
}

Upvotes: 2

Rik Heywood
Rik Heywood

Reputation: 13972

Try looking at HoverIntent. http://cherne.net/brian/resources/jquery.hoverIntent.html

This makes it quite easy to perform actions a delay after the user has stopped interacting with your menu.

Upvotes: 2

Sam Wessel
Sam Wessel

Reputation: 8858

Unfortunately jQuery doesn't have a delay function. However, you can use a sneaky and not-too-dirty hack to simulate a delay, by animating the opacity of an element from 1 to 1:

$('#visibleElement')               // Assuming the element is already shown
  .animate({opacity: 1.0}, 3000);  // do nothing for 3 seconds

So to slide up your menu 5 seconds after the mouse leaves you could do the following:

$('#menuDiv').mouseout(function(){
  .animate({opacity: 1.0}, 5000)
  .animate( slide up etc...
});

Upvotes: 2

Related Questions