Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery binding click event best practices

Tags:

jquery

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?

like image 767
Joel Avatar asked Jul 19 '12 00:07

Joel


People also ask

What is bind event in jQuery?

For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs.

How to bind click event to a specific element in Dom?

It will work because you attach it to every specific element. This is why you need - after adding your link to the DOM - to find a way to explicitly select your added element as a JQuery element in the DOM and bind the click event to it. The best way will probably be - as suggested - to bind it to a specific class via the live method.

What happened to bind() method in jQuery?

As of jQuery 3.0,.bind () has been deprecated. It was superseded by the.on () method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged. For earlier versions, the.bind () method is used for attaching an event handler directly to elements.

What are the best practices when using jQuery?

It’s good practice to check the element but not obvious code. I recommend always check the element while using jQuery plugin such as a slider, data table etc. It saves your app from errors. 9. Optimize Selectors jQuery selectors allow you to select and manipulate HTML element (s) quite easily. Some jQuery methods use browser native method.


2 Answers

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.

like image 123
Fresheyeball Avatar answered Oct 20 '22 01:10

Fresheyeball


You can take a quick look at the source and see for yourself what your function call actually does.

Inside jQuery objects' extend (line 3754), jQuery iterates over all these method names at line 3909:

blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu

Creating the shorthand methods which call the .on method for the given method without passing a selector attribute when those methods are invoked (line 3921):

this.on( name, null, data, fn )

Which just means it'll have no event delegation effect.


What have you found to be the best practices when binding events that have shortcuts in jQuery? Use the shortcut or do it yourself?

The only difference between calling

$(selector).eventname(function(){...})

And

$(selector).on('eventname', function(){...})

Is that the shorthand method has the overhead of another function call (which is negligibly minimal).

Update: When making a custom build of jQuery with Grunt, the shorthand methods can be excluded with the custom:-event-alias parameter for an even smaller build (Docs here). Though, I personally tend to stick with the CDN builds.


As for how event delegation works and when it is preferred, check the docs and @Fresheyeball's answer.

like image 32
Fabrício Matté Avatar answered Oct 20 '22 01:10

Fabrício Matté