Reputation: 4049
I have a simple tile. Upon click, the tile gets filled in with content B instead of content A, and on click again, the tile gets filled back in with content A instead of content B.
This is the jQuery code:
$(".switch").on('click', function() {
toggleBrand($(this));
})
function toggleBrand(_this) {
_this.children().not(".no-display").toggle();
_this.children(".no-display").toggle();
}
What I would now like is for the second "click" to happen automatically. I.e., when you click the object, content B shows instead of A, then there's a 2 second delay, and content A shows instead of content B again without you having to click.
I tried using a setTimeout
as below:
$(".switch").on('click', function() {
_this = $(this)
toggleBrand(_this);
setTimeout(toggleBrand(_this),2000);
})
But the fiddle breaks with a setTimeOut undefined
even though I cased it correctly... Am I not using setTimeout
correctly?
Fiddle here: https://jsfiddle.net/v018hh52/2/
Upvotes: 1
Views: 226
Reputation: 5897
jsfiddle : https://jsfiddle.net/v018hh52/5/
All you needed to do was fix your setTimeout
call :(, basically you provide setTimeout with a function which will call your function, if you provide your function like you are doing at the moment it will be called asap instead of in 2000 (2 seconds)
So just change your setTimeout
call to look like this
setTimeout(function() {
toggleBrand($this)
}, 2000);
And that should do the trick. Also I updated your CSS, because you keep clicking it will highlight the content and then you can no longer see it.
P.S. also you may want to set a flag when you run this code as the user can keep clicking on the div and it will get the setTimeout
in a puzzle. Also if this content is generated from another script you may want to make a global event listener on 'document'
Upvotes: 2
Reputation: 1948
As an alternative to webdeb's answer you could also bind the parameter to the function like this:
setTimeout(toggleBrand.bind(null, _this), 2000);
Or completely remove the _this
parameter and just use this
in the toggleBrand
function this way:
setTimeout(toggleBrand.bind(_this), 2000);
With the toggleBrand
function implemented as:
function toggleBrand() {
this.children().not(".no-display").toggle();
this.children(".no-display").toggle();
}
Upvotes: 1
Reputation: 13211
Yes, you are using setTimeout wrong
You are passing the return value of the function, instead you should pass a function.
$(".switch").on('click', function() {
_this = $(this)
toggleBrand(_this);
setTimeout(function() { toggleBrand(_this) },2000);
// OR, thanks @4castle for his comment
setTimeout(toggleBrand, 2000, _this);
})
Explanation
function foo() { return "value" };
foo // -> function
foo() // -> "value"
Upvotes: 2