I have tried to search for an answer to this, but my wording is too similar to the questions that are looking for event delegation using the jQuery on()
method. Consequently, please do not get confused by the wording of my question.
I feel ashamed that I am actually asking this question given my experience with writing jQuery applications, but I must confess that I do not actually know the answer to this :-(
Consider this:
// Create the div
$('#wrapper').prepend('<div id="test"></div>');
// Add content to the div, and attach events
// Only execute it once the div has been created though, so wait 20 milliseconds
setTimeout(function(){
// Add some button
$('#test').html('<button></button>');
// Add an event to the button
// ... after 20 milliseconds
setTimeout(function(){
// Attach the click event
$('#test button').click('dosomething');
});
},20);
In the above code, I have had to use setTimeout
to ensure that the element has been created before selecting it and adding content, events etc...
My question, quite simply, is there a better way to do this? Without timeouts?
Please note I do not mean, is there a better way to write the exact code above? I simply want to know if there is a way to avoid using timeouts for the reason specified.