views:

637

answers:

4

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?

+2  A: 

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;
}
Ronald Wildenberg
+1  A: 

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...
});
Sam Wessel
Wouldn't this hide the menu after 5 seconds without regard to inactivity? As far as I got the question, it was more to the logic about setting timeout starting from inactivity...
peirix
Fair point. Edited my example to be on mouseout instead of pageload.
Sam Wessel
the opacity hack has seemed to work fine, it gives me the 5 seconds of position i want before the menu animates upwards, nice one!
DanC
+2  A: 

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.

rikh
+1  A: 

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