Green Files

What's the difference between .on("click", function() {}) and the .click(function() {})?

Day: 06/01/2022 - Time: 15:31:57

It's basically how the binding to the element is done. .click applies to the current DOM, while .on (using delegation) will continue to apply to new elements added to the DOM after event binding.

Which one is better to use, I would say it depends on the case.

Example:

<ul id="todo"> <li>To-do 1</li> <li>To-do 2</li> <li>To-do 3</li> <li>To-do 4</li> </ul>

.click event:

$("#todo li").click(function() { $(this).remove(); });

.on event:

$("#todo").on("click", "li", function() { $(this).remove(); });

Note that I separated the selector in the .on. I'll explain why.

Suppose that after this association, we do the following:

$("#todo").append("<li>To-do 5</li>");

That's where you'll notice the difference.

If the event was linked via .click, to-do 5 will not obey the click event, and thus will not be removed.

If it was bound via .on, with the selector separated, it will obey.

Reference:

https://pt.stackoverflow.com/questions/5196/qual-a-diferen%c3%a7a-entre-o-onclick-function-e-o-clickfunction

GO UP
GO TO INDEX