Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `$(document).on("click", "a"` and `$("a").click(` [duplicate]

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)
});
like image 663
Sreepathy Sp Avatar asked Oct 22 '15 10:10

Sreepathy Sp


People also ask

What is difference between .on and .click in JavaScript?

. click events only work when element gets rendered and are only attached to elements loaded when the DOM is ready. . on events are dynamically attached to DOM elements, which is helpful when you want to attach an event to DOM elements that are rendered on ajax request or something else (after the DOM is ready).

What is difference between Onclick and click?

click is a function on HTML elements you can call to trigger their click handlers: element. click(); onclick is a property that reflects the onclick attribute and allows you to attach a "DOM0" handler to the element for when clicks occur: element.

What is the difference between .click and .on (' click in jQuery?

So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.

What is difference between $( document .ready function () vs $( function ()?

The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.


2 Answers

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

like image 71
Tushar Avatar answered Oct 22 '22 05:10

Tushar


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.

like image 29
Saar Avatar answered Oct 22 '22 06:10

Saar