I think it has to do with personal preference and code readability more than anything.
As far a more powerful goes .on
lets you delegate events while shortcuts always operate on the element directly. For example $('body').on('click', '.button', function(){});
will work for every .button
element even those added after the fact with ajax or otherwise. While the shortcut cannot do this $('.button').click(function(){});
is the only way to add a listener to .button
and does not feature delegation, so .button
elements added later will not have this binding.
Direct un-delegated events (like shortcuts) on multiple elements is also slightly less efficient then delegated events on a parent object. For example: lets say there are 15 .button
elements on the page, $('.button').click(...
will loop through all 15 elements and add an event listener to each; however $('#parentElem').on('click', '.button', ...
will simply attach a single event listener to #parentElem
that checks on the target, so one attach and one listener, vs a loop and 15 listeners.
And finally, .on
has the advantage of allowing you to attach a function to an element from multiple events, which is not possible with shortcuts, for example: $('.button').on('click mouseover keyup', ...
the function will trigger with click, mouseover or keyup!
Lets again say there are 15 .button
elements in a div called #parent
Shortcut handler:
$('.button').click(turnRed);
$('.button').mouseover(turnRed);
$('.button').keyup(turnRed);
function turnRed(){
$(this).css('color','red');
}
- 4 jQuery objects created (yes I know you could cache it to 2 objects but this is an example)
- 3 element loops of 15 each, so jQuery hits elements here 45 times and attaches listeners
- 45 total event listeners
- future
.button
elements added to the scene do not turnRed
.on
handler:
$('#parent').on('click mouseover keyup', '.button', turnRed);
function turnRed(){
$(this).css('color','red');
}
- 2 jQuery objects created
- No element loop, so jQuery hits elements once
- 3 total event listeners
- future
.button
elements add to the scene will in fact turnRed
Here .on
clearly has the advantage
If your situation is simpler than this, then the advantage of .on
may not make a difference to you, and the shortcut may be preferred as its more readable.
$('#button').click(...
is nearly identical to $('#button').on('click', ...
(see @Fabrício Matté's answer) and if we just want to add one listener to one event, the .on
's power is a moot point.
Personally because there are times when I want the advantage of .on
I always use .on
just to be consistent.