kumardeepakr3
kumardeepakr3

Reputation: 395

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>
</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/

Upvotes: 0

Views: 83

Answers (2)

Matt Way
Matt Way

Reputation: 33171

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():

selector

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.

Upvotes: 1

Prasanna
Prasanna

Reputation: 11544

If you are wondering how the click works on an element which is not there at the time of page load, then that's because you are attaching the listener on the outerDiv and using .on

Check out this for the difference between using .on and .click

Upvotes: 1

Related Questions