jQuery

Why use jQuery on() instead of click()

Share

The on() method attaches one or more event handler functions for one or more events to the selected elements.

Event handlers attached using the jQuery on() method will work for both current and future elements i.e. dynamic element created by a script.

Note: As of jQuery version 1.7, the jQuery on() method is the new replacement for the jQuery bind(), live() and delegate() methods.

To attach an event to the selected element that only runs once and then removes itself, you can use the one() method.

Syntax:
$(selector).on(event, childSelector, data, function, map)

So, why use jQuery on() instead of click()? Any idea?

Because you might have a dynamically generated elements (for example an AJAX call), you might want to have the same click handler that was previously bound to the same element selector You then “delegate” the click event using on() with selector argument.

Get more details from jQuery documentation.

Below example can describe the problem easily.

Suppose you have following HTML:

<ul id=”click”>

<li>List item with click</li>

</ul>

<ul id=”on”>

<li>List item with on</li>

</ul>

And this is the script:

$(‘#click li’).click(function() {

$(this).parent().append($(‘<li>List item with click</li>’));

});

$(‘#on’).on(‘click’, ‘li’, function() {

$(this).parent().append($(‘<li>List item with on</li>’));

});

So, in this case, if you click on “<li>” within id “on” then you can append “<li>” within that id. Again if you click on dynamic appended “<li>” then you can also append “<li>” within that id.

But, if you click on “<li>” within id “click” then you can append “<li>” within that id. Again if you click on dynamic appended “<li>” then you can not append “<li>” within that id as this is added in future. Only clicking on first “<li>”, you can append “<li>”.

Recent Posts

The Sharp-Looking Guy: 5 Essential Tips for Men to Become Sharp

We've gotten so used to seeing men streetwear joggers, ripped jeans, and sleeveless shirts. Hair…

22 hours ago

How to Use Your Wedding Jewellery In Unique Ways At Festivals

When it comes to festivals, the options for wedding jewellery are endless. You can go…

23 hours ago

5 Tips On Window Cleaning

Whether it concerns your home or an office building, the state of a property’s windows…

1 day ago

Sustainable Business Practices: A Win-Win Strategy

You know that running an environmentally sustainable business is the right thing to do. But…

1 day ago

Unlock Growth – Guide to Online Financing and Business Loans for Entrepreneurs

If you are in a financial crisis , or need to start a new business…

1 day ago

7 Key Factors That Help In Selecting the Best Fleet Management Software

To realize the strategic advantage from the fleet management system (FMS) and differentiate the business…

1 day ago