0

I usually use it, because I learned that it was the most correct, event assignment as follows:

$('selector').on('click', function () {});

However, I see many developers using the following syntax:

$('selector').click(function () {});

Although they told me that .on is the most recommended, I did not quite understand why. So, in practice, what's the difference in using one or the other?

Lucas
  • 275
  • 8
  • 37

1 Answers1

2

It's basically how association is made to the element. .click applies to the current DOM, while .on (using delegation) will continue to be valid for new elements added to the DOM after event association.

Which is better to use, I'd say it depends on the case.

Example:

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

.Click Event:

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

Event .on:

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

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

Let us suppose that after this association, let us do the following:

$("#todo").append("<li>Do 5</li>");

That is where you will notice the difference.

If the event was associated via .click, task 5 will not obey the click event, and so it will not be removed.

If it was associated via .on, with the selector separate, it will obey.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Lucas
  • 275
  • 8
  • 37