Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any disadvantages when using ".on"?

Tags:

jquery

I hope this wasn't asked yet, i didn't find anything via google and I'm really curious. Yesterday i encountered an error. My code looked like this:

$(".button").click(function(){
    //Do something!
});

The problem was, that the class .button was loaded via AJAX later on, so the event did never fire. I solved it with this approach:

$("body").on("click", ".button", function() {
    //Do something!
});

So since yesterday, I'm thinking about what the advantages of the first approach are (except a few characters less). Is it a bad practice to attach all the handlers to the body and fire them only at specific elements? Or is there any reason why i should not use .on() the whole time which might break my code?

like image 211
Realitätsverlust Avatar asked Sep 18 '14 06:09

Realitätsverlust


2 Answers

.on can also work with dynamically added dom objects

In older versions of Jquery we were using .live, .bind or .click etc but now preferred is .on

read the detail here

http://api.jquery.com/on/

Difference between .on('click') vs .click()

like image 148
Jason W Avatar answered Nov 12 '22 11:11

Jason W


"Is it a bad practice to attach all the handlers to the body and fire them only at specific elements?"

Yes, it is bad practice to use delegates for every event. For each delegate that you add to the body, the selector will be evaluated every time that event happens anywhere in the page.

The preferred way to bind events is like in your first example (or doing the equivalent with the on method), as that will bind the event directly to the element. There is no selector that needs to be evaluated when the event happens.

Using delegates once in a while is a convenient way to handle situations like the one that you had, but if you start to get many delegates in the page you should consider binding them directly to the element instead.

like image 2
Guffa Avatar answered Nov 12 '22 09:11

Guffa