I want to set timeouts dynamically in jQuery. The dynamically set timeout functions need to use $("this"), but I can't seem to get it working.
An exmple:
$("div").each(function(){
var content = $(this).attr('data-content')
setTimeout("$(this).html('"+content+"')",$(this).attr('data-delay'));
});
http://jsfiddle.net/qmhmQ/
What is the best way to do this?
$("div").each(function(){
var content = $(this).attr('data-content'),
$this = $(this); // here $this keeps the reference of $(this)
setTimeout(function() {
// within this funciton you can't get the $(this) because
// $(this) resides within in the scope of .each() function i.e $(this)
// is an asset of .each() not setTimeout()
// so to get $(this) here, we store it within a variable (here: $this)
// and then using it
$this.html(content);
}, $this.attr('data-delay'));
});
DEMO
Your code should look like this:
pass a function instead of a string. Explanation: When passing a string to setTimeout you get problems, because it runs in a different scope than you original one, and thus you get errors.
use the jQuery data()
method
$("div").each(function(){
var content = $(this).attr('data-content'),
$el = $(this),
setContent = function(){
$el.html(content);
}
setTimeout(setContent,$el.data('delay'));
});
You can assign a function to a variable and pass that variable as parameter to setTimeout, this is the cleanest way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With