Using jQuery on() version 1.7. I bind my events usually like this:
$(".foo").on("click", function() {
console.log("foo clicked");
})
Now after seeing someone elses code, I seen you also can bind like this, specifying a secondary parameter for a specific element (Not sure why it was written like this):
$(document).on("click", ".bar", function() {
console.log("bar clicked");
})
As seen in this fiddle, they both do the same thing.
I always bind directly to the element as in the first code sample and never have any issues.
When would I need to use the other way of binding and what is the benefit of one over the other?
Your second code example is equivalent to the deprecated now
.live()event. So you will use it situations when you want to subscribe to events of DOM elements that don’t yet exist in the DOM in the moment of subscription (think for example elements added to the DOM after an AJAX call).Your first example is perfectly equivalent to
$(".foo").click(function() { ... });.