Drhodes
Drhodes

Reputation: 191

Jquery if not clicked after (x) seconds execute function automatically

I have a function that executes to slide open a couple divs to reveal the content behind. There is a button that when clicked activates the function to reveal said content. I'm trying to figure out how to execute that function automatically if the button isn't clicked on after 7 seconds. Any help would be much appreciated.

Here's what I've got.

$(document).ready(function() {

        $(".button").click(function(){
                $(this).fadeOut('slow'); 
                    $(".leftside").animate({width:'60px'}, 500 );
                    $(".rightside").animate({width:'60px'},500 );
        });

    }); 

Upvotes: 1

Views: 2143

Answers (3)

Mak
Mak

Reputation: 20453

$(document).ready(function() {

        setTimeout( showThis(), 7000 );

        $(".button").click(showThis);

        function showThis(){
                $(".button").fadeOut('slow'); 
                    $(".leftside").animate({width:'60px'}, 500 );
                    $(".rightside").animate({width:'60px'},500 );
        });

    }); 

Upvotes: 0

Mrchief
Mrchief

Reputation: 76218

Add a timer:

var timer = setTimeout(function() { $(".button").click(); }, 7000);

And clear it in your button click:

clearTimeout(timer);

Full code:

$(document).ready(function() {
    var timer = setTimeout(function() { $(".button").click(); }, 7000);
    $(".button").click(function(){
            clearTimeout(timer);
            $(this).fadeOut('slow'); 
                $(".leftside").animate({width:'60px'}, 500 );
                $(".rightside").animate({width:'60px'},500 );
    });
});

Upvotes: 7

Johnny Craig
Johnny Craig

Reputation: 5002

$(document).ready(function() {
    var myclick=setTimeout(function(){
        $(".button").click();
     }, 7000);
    $(".button").click(function(){
            clearTimeout(myclick);
            $(this).fadeOut('slow'); 
                $(".leftside").animate({width:'60px'}, 500 );
                $(".rightside").animate({width:'60px'},500 );
    });

});

Upvotes: 1

Related Questions