circey
circey

Reputation: 2042

jquery function after setTimeout

I have a dropUp menu with the following:

$(document).ready(function(){
var opened = false;
$("#menu_tab").click(function(){
    if(opened){
        $("#menu_box").animate({"top": "+=83px"}, "slow");
        setTimeout(function(){
                $("#menu_box").animate({"top": "+=83px"}, "slow");
                }, 2000);
                clearTimeout();
    }else{
        $("#menu_box").animate({"top": "-=83px"}, "slow");
    }
    $("#menu_content").slideToggle("slow");
    $("#menu_tab .close").toggle();
    opened = opened ? false : true;
});
});

So after clicking on the menu_tab, the menu drops up and stays up until clicked again, but I'd like a timeout so that after say 2 seconds the menu drops down again.

I've obviously got the coding wrong because the timeout isn't working. Any help would be appreciated! TIA.

Upvotes: 2

Views: 2519

Answers (3)

user113716
user113716

Reputation: 322592

I think you are trying to do something like this:

Try it out: http://jsfiddle.net/YFPey/

var opened = false;
var timeout;
$("#menu_tab").click(function() {
      // If there's a setTimeout running, clear it.
    if(timeout) {
        clearTimeout(timeout);
        timeout = null;
    }
    if(opened) {
        $("#menu_box").animate({"top": "+=83px"}, "slow");
    } else {
        $("#menu_box").animate({"top": "-=83px"}, "slow");
             // Set a timeout to trigger a click that will drop it back down
        timeout = setTimeout(function() {
            timeout = null;
            $("#menu_tab").click();
        }, 2000);
    }
    $("#menu_content").slideToggle("slow");
    $("#menu_tab .close").toggle();
    opened = !opened;
});​

Upvotes: 1

Brad Robinson
Brad Robinson

Reputation: 46937

Two things that stand out to me:

  1. Because opened starts out as false, the timer only gets started on the second click.
  2. In the timer handler, should you be updating opened.

Upvotes: 0

thomasrutter
thomasrutter

Reputation: 117401

Your use of clearTimeout() here is wrong. You need to pass it a reference to the ID returned when you created that timer with setTimeout().

Can't say if that's causing your problem though (it probably isn't). If you get anything in the Javascript error console that might help.

Upvotes: 0

Related Questions