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?
.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()
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With