Lately when binding click events in jQuery I find myself questioning whether to use the jQuery shortcut click() or if I should specify the .on('click', ...) call myself.
The .click(). function in jQuery is just a shortcut. To me it makes sense to use because jQuery handles everything behind the scenes accounting for the preferred method per the version of jQuery being used. When I upgraded my scripts from jQuery 1.6 -> 1.7 I know that all of my click()s went from being a shortcut to bind() to the preferred on() method. This, alone, seems reason enough to use the shortcuts.
…however….
Trevor Burnham, whom I greatly respect, says in his eBook Async Javascript that he
… prefer(s) to consistently use the more powerful bind/on) (over click)
That confuses me and I was wondering why using bind/on is ‘more powerful’.
What have you found to be the best practices when binding events that have shortcuts in jQuery? Use the shortcut or do it yourself?
I think it has to do with personal preference and code readability more than anything.
As far a more powerful goes
.onlets you delegate events while shortcuts always operate on the element directly. For example$('body').on('click', '.button', function(){});will work for every.buttonelement 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.buttonand does not feature delegation, so.buttonelements 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
.buttonelements 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#parentElemthat checks on the target, so one attach and one listener, vs a loop and 15 listeners.And finally,
.onhas 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
.buttonelements in a div called#parentShortcut handler:
.buttonelements added to the scene do notturnRed.onhandler:.buttonelements add to the scene will in factturnRedHere
.onclearly has the advantageIf your situation is simpler than this, then the advantage of
.onmay 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
.onI always use.onjust to be consistent.