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?