I'm new to jQuery and wrote the following code. Strangely, the jQuery code somehow works even after the time delay. alert() gets called onclick after the time delay. The same thing in javascirpt with .addEventListener() would give error since the element doesn't exist. Can someone explain me how and why jQuery does this?
<div id="outerId" class="outerHolder">
<div class="innerHolder"></div>
</div>
JS Code:
$("#outerId").on("click touchstart", "#newTag", function (e) {
alert("OK");
});
setTimeout(function() {
var tag = '<div id="newTag">Hello World</div>';
$("#outerId").append(tag);
}, 5000);
Here is a jsFiddle of the same: https://jsfiddle.net/jb6pmovb/