10

Can Anybody tell me what will be the difference between these two script,Am not a javascript/jquery expert.

$(document).on("click", "a", function () {
    i = $(this).data("value");
    alert(i)
})

$("a").click(function () {
    i = $(this).data("value");
    alert(i)
});
1
  • I Think 1st one will be for dynamically coming ones Commented Oct 22, 2015 at 10:49

3 Answers 3

31

$(document).on("click", "a", function () { will bind the event on the a elements which are not present at the time of binding event. This is called as event delegation.

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

Whereas $("a").click(function () { will bind events only to the a elements which are present in DOM.

3

The first one will check every click on the document and check if it's from an "a" tag and if so perform the code, this will be also relevant for dynamically created "a" tags.

The second will perform the code only for "a" elements which already existing on the page.

3

The first one gives event delegation i.e. it will bind event with element those exist in DOM and fulfill the selection criteria + any element that is added in DOM after the event is binded (meeting the selector criteria) will get binded automatically as it is added to DOM on fly.

While the later will bind event with existing elements.

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

Not the answer you're looking for? Browse other questions tagged or ask your own question.