Reputation: 407
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?
Upvotes: 3
Views: 81
Reputation: 206058
$(document).on("click", ".bar", function() {
console.log("bar clicked");
});
it's instead of the now deprecated .live()
method
it's for delegating your event handler directily to element/s (dynamically generated 'on the go')
If you use $('.button').on('click',function(){
and let's say you generate dynamically a button - the click on that element will do nothing.
If you use $('#navigation').on('click','.button',function(){
the click handler is being attached (delegated) to any present and future .button
element making it clickable.
Where $(document)
(it's slower) can be your parent element: $('#your_parent')
(faster)
Upvotes: 3
Reputation: 9080
Always use the nearest parent element. jQuery watches the events bubbling up and attaches them as soon as it finds one, this is called Event Delegation. When you use document
which is also default, jQuery has to wait until that instead of closest parent element of the clicked element.
Your first example works for elements that are supposed to be present there when you bind an event to them while later approach works for both present and newly/dynamic created elements
Upvotes: 2
Reputation: 1038730
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() { ... });
.
Upvotes: 4