I set up an simple experiment out of curiosity:
I dynamically generated a div with the class
box
before attaching a click listener to it with JQuery.I then created a duplicate of this, except this time, I added a timeout of zero before the
box
element is generated.
As shown in the JSFiddle, using a timeout of zero results in the failure of the click's intended result event to be triggered.
This script results in an alert on click.
$(document).ready(function(){
//setTimeout(function(){
$(".wrapper").html('<div class="box"></div>');
//},0)
$(".box").click(function(){
console.log("A box was clicked!");
});
});
This script does not.
$(document).ready(function(){
setTimeout(function(){
$(".wrapper").html('<div class="box"></div>');
},0)
$(".box").click(function(){
console.log("A box was clicked!");
});
});
Why does a timeout of zero cause the element to be (I assume) generated after the click event listener is attached via JQuery?
Does setTimeout(functon(){//do stuff},0)
cause a minuscule execution delay for it's contained function? If so, why does this happen?