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)
});
. 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).
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.
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.
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.
$(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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With