Deepak Kumar Deepak Kumar - 3 months ago 26
Javascript Question

Why does jQuery behave differently than javascript?

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>

JS Code:

$("#outerId").on("click touchstart", "#newTag", function (e) {

setTimeout(function() {
var tag = '<div id="newTag">Hello World</div>';
}, 5000);

Here is a jsFiddle of the same:


My guess is that your query is about the way on() is binding to to the object. When on() is first ran, #newTag does not exist, so you might be wondering why it still triggers when appended after a delay.

This is because #outerId is the object being bound to, which does exist the time on() is called. When you append #newTag, it doesn't alter the outer binding, it simply looks over the children when it is clicked.

With regular js I assume you are using addEventListener, which requires you bind the event to the specific object. If you do try and use that directly on #newTag before it exists, it obviously won't work.

You can see by the docs for on():


Type: String A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.