9

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)
});
Tushar
  • 78,625
  • 15
  • 134
  • 154
Sreepathy Sp
  • 388
  • 2
  • 3
  • 20

3 Answers3

24

$(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.

Tushar
  • 78,625
  • 15
  • 134
  • 154
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.

Adil
  • 139,325
  • 23
  • 196
  • 197
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.

Saar
  • 2,216
  • 1
  • 13
  • 14