Reputation: 6217
Here are two different ways of writing event handlers:
$('element').on("click",function(){
// do stuff
});
vs
$('element').click(function(){
// do stuff
});
What are the key differences between the two? What situations would one be better suited than the other?
Upvotes: 0
Views: 75
Reputation: 13681
According to jQuery's API documentation
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()
The .on(...)
function utilizes all the other event binding mechanisms. It should always work. According to jQuery's API documentation
This method is a shortcut for .on( "click", handler ) in the first two variations, and .trigger( "click" ) in the third. The click event is sent to an element when the mouse pointer is over the element, and the mouse button is pressed and released. Any HTML element can receive this event. For example, consider the HTML:
.click(...)
is a shortcut to element.on("click", ...)
Upvotes: 1
Reputation: 1212
click() is a convenience shortcut for on(). The only way it differs from on() is that if you call it with no parameters it will call:
$(element).trigger('click');
Upvotes: 0