hbowman
hbowman

Reputation: 307

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>

Upvotes: 0

Views: 2391

Answers (4)

bevacqua
bevacqua

Reputation: 48476

$('.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(function(){
            var self = $(this);
            setTimeout(function() {
                self.slideUp(); 
            },5000);
        });
    }
});

doing it like this would preserve the behavior you originally wanted: waiting 5 seconds after the .slideDown animation completes, before sliding up.

Upvotes: 2

xthexder
xthexder

Reputation: 1565

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/

Upvotes: 1

Elliot Bonneville
Elliot Bonneville

Reputation: 53301

Try this in your click function:

if (container.is(':hidden')) {
    // Show - slide down, pause 5 seconds, slide up
    container.slideDown();
    setTimeout(function(){
        container.slideUp();     
    },5000);
}

Upvotes: 1

gilly3
gilly3

Reputation: 91497

Use setTimeout:

container.slideDown();
setTimeout(function () {
    if (container.is(":visible")) {
        container.slideUp();
    }
}, 5000);

Upvotes: 3

Related Questions