Search code examples
jquerydelayslide

Collapse jquery panel after 5 seconds, or allow manual close on click


I am trying to have a panel slide open and close on click of a link, but I also want the panel to collapse after 5 seconds if the user hasn't done anything. I have this sort of working with .delay, but during that 5 seconds, I can't toggle the panel close with the .seriesLink because I don't know how to intercept the delay. So basically the panel is stuck open for 5 seconds right now even if the user tries to close it by clicking the Series link again. Here is my HTML and jQuery:

var container = $('.menu');
    $('.seriesLink').click(function( event ){
        // Prevent the default event
        event.preventDefault(); 
        // Toggle the slide based on its current visibility.
        if (container.is( ":visible" )){
            // Hide - slide up
            container.slideUp( );
        } 
        if (container.is(':hidden')) {
            // Show - slide down, pause 5 seconds, slide up
            container.slideDown().delay(5000).slideUp(); 
        }
    });
<a href="#" class="seriesLink">Series</a>
<div class="menu">
  <ul class="subMenu">
    <li><a href="http://www.google.com">Link title</a></li>
    <li><a href="http://www.google.com">Link title</a></li>
    <li><a href="http://www.google.com">Link title</a></li>
  </ul>
</div>

Solution

  • The delay function will stop all javascript in the current context from running. You need to use setTimeout to schedule a future event.

    I implemented a version in this jsfiddle that will cancel any previous events if the link is clicked more than once:

    http://jsfiddle.net/FtqG8/