What is the difference between $('.botao'). on('click') and $(Document). on('click', '.botao')?

Asked

Viewed 416 times

0

I did a search and could not find anything about (probably because I’m not sure how to search). Anyway, someone there knows?

NOTE: I don’t want to know the difference between . click and . on('click'), please read the two options carefully. What I want to know is the difference of referencing the element that will receive the action before saying what the action or after (putting Document in the place that before was the element).

$('.botao').on('click') and $(document).on('click', '.botao')

  • What you understood from documentation where it deals with the second function parameter?

  • 2

    Diego is not the same question, I had seen this question already, her doubt is the difference between . click and on. ('click'). My question is about the difference of putting $(Document) in place of the element that receives the action, and referencing the element afterwards. If you notice the two calls in my question use the . on('click')..

  • 1

    Hi Thavi, the difference in this case would be that '$('.botao')' Voce is only doing an action in this class, recommended use for when you want to add an action in a specific element. Already the '$(Document). on('click', '.boot')' you are executing the action throughout the page in case there is more than one element with the class put in the page and when it is clicked this action will be triggered. Document = pages.extensao window = page loaded . button (only) = element identifier.

2 answers

5


When you use the:

$('.botao').on('click');

You are linking the click event to each element that contains the class ". button" already existing in the document. The main problem of this method is that if you need to add an element dynamically with the same class ". boot", it will not own the click event, as it was added to the document afterwards.

And as for the:

$(document).on('click', '.botao');

In this case, the click event is linked to the document itself, and not to the class specific elements ". botao". This is the most recommended method to use, as when adding new elements to the document they will still have the reference of the click event linked to the document.

  • So actually the difference is what people were saying that was the difference from . click and on(click') [which in the jquery documentation says are the same]...

  • I believe . click and . on('click') are described as equal because they perform the same function. The difference is even in the scope in which they are applied (and in Event target).

  • 1

    Got it. Thank you :D

2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.