Why Use Jquery On() Instead of Click()

Why use jQuery on() instead of click()

Because you might have a dynamically generated elements (for example coming from an AJAX call), you might want to have the same click handler that was previously bound to the same element selector, you then "delegate" the click event using on() with selector argument

To demonstrate:

http://jsfiddle.net/AJRw3/

on() can also be synonymous with click() if you don't have a selector specified:

$('.elementClass').click(function() { // code 
});

is synonymous with

$('.elementClass').on('click', function() { // code
});

In the sense that it only add the handler one time to all elements with class elementClass. If you have a new elementClass coming from, for example $('<div class="elementClass" />'), the handler won't be bound on that new element, you need to do:

$('#container').on('click', '.elementClass', function() { // code
});

Assuming #container is .elementClass's ancestor

Difference between .on('click') vs .click()

I think, the difference is in usage patterns.

I would prefer .on over .click because the former can use less memory and work for dynamically added elements.

Consider the following html:

<html>
<button id="add">Add new</button>
<div id="container">
<button class="alert">alert!</button>
</div>
</html>

where we add new buttons via

$("button#add").click(function() {
var html = "<button class='alert'>Alert!</button>";
$("button.alert:last").parent().append(html);
});

and want "Alert!" to show an alert. We can use either "click" or "on" for that.


When we use click

$("button.alert").click(function() {
alert(1);
});

with the above, a separate handler gets created for every single element that matches the selector. That means

  1. many matching elements would create many identical handlers and thus increase memory footprint
  2. dynamically added items won't have the handler - ie, in the above html the newly added "Alert!" buttons won't work unless you rebind the handler.

When we use .on

$("div#container").on('click', 'button.alert', function() {
alert(1);
});

with the above, a single handler for all elements that match your selector, including the ones created dynamically.


...another reason to use .on

As Adrien commented below, another reason to use .on is namespaced events.

If you add a handler with .on("click", handler) you normally remove it with .off("click", handler) which will remove that very handler. Obviously this works only if you have a reference to the function, so what if you don't ? You use namespaces:

$("#element").on("click.someNamespace", function() { console.log("anonymous!"); });

with unbinding via

$("#element").off("click.someNamespace");

jQuery.click() vs onClick

Using $('#myDiv').click(function(){ is better as it follows standard event registration model. (jQuery internally uses addEventListener and attachEvent).

Basically registering an event in modern way is the unobtrusive way of handling events. Also to register more than one event listener for the target you can call addEventListener() for the same target.

var myEl = document.getElementById('myelement');

myEl.addEventListener('click', function() {
alert('Hello world');
}, false);

myEl.addEventListener('click', function() {
alert('Hello world again!!!');
}, false);

http://jsfiddle.net/aj55x/1/

Why use addEventListener? (From MDN)

addEventListener is the way to register an event listener as specified
in W3C DOM. Its benefits are as follows:

  • It allows adding more than a single handler for an event. This is particularly useful for DHTML libraries or Mozilla extensions that
    need to work well even if other libraries/extensions are used.
  • It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
  • It works on any DOM element, not just HTML elements.

More about Modern event registration -> http://www.quirksmode.org/js/events_advanced.html

Other methods such as setting the HTML attributes, example:

<button onclick="alert('Hello world!')">

Or DOM element properties, example:

myEl.onclick = function(event){alert('Hello world');}; 

are old and they can be over written easily.

HTML attribute should be avoided as It makes the markup bigger and less readable. Concerns of content/structure and behavior are not well-separated, making a bug harder to find.

The problem with the DOM element properties method is that only one event handler can be bound to an element per event.

More about Traditional event handling -> http://www.quirksmode.org/js/events_tradmod.html

MDN Reference: https://developer.mozilla.org/en-US/docs/DOM/event

jquery use of bind vs on click

From the documentation of bind and click :

bind :

As of jQuery 1.7, the .on() method is the preferred method for
attaching event handlers to a document.

The source makes it clear there's no reason to use bind, as this function only calls the more flexible on function without even being shorter :

bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},

So I'd suggest, just like the jQuery team, to forget the old bind function, which is now useless. It's only for compatibility with older code that it's still here.

click :

This method is a shortcut for .on('click', handler)

This shortcut is of course less powerful and flexible than the on function and doesn't allow delegation but it lets you write a shorter and, arguably, slightly more readable, code when it applies. Opinions diverge on that point : some developers argue that it should be avoided as it is just a shortcut, and there's also the fact that you need to replace it with on as soon as you use delegation, so why not directly use on to be more consistent ?

jquery on vs click methods

It's not specifically worth replacing click(), as in the jQuery source it converts all the 'shortcut' event handlers (like click(), keyup() etc.) to on("event", fn) anyway.

jQuery - Calling .trigger('click') vs .click()

If you're using .trigger() you have the advantage of being able to pass additional parameters, whereas .click() must be called without any.

Taken from the documentation:

$('#foo').bind('custom', function(event, param1, param2) {
alert(param1 + "\n" + param2);
});
$('#foo').trigger('custom', ['Custom', 'Event']);

'Custom' and 'Event' are being passed to the event handler as param1 and param2 respectively

Besides that, the .click() is unlike other functions that implement get / set based on the number of arguments, because it implements trigger / set instead. Using a dedicated .trigger(), to me, is more logical.

When using jQuery on(), why use (document) vs. the element itself?

Both of those are valid.

The former works for dynamically added elements. You use document because you're delegating events on children of the document object, so events bubble up to the document level. It's also more convenient to select the closest parent you can (and the parent must exist on the page at load).

The latter still works, and is a preferred way to simply bind events to specific elements.

I personally don't recommend delegating through the document object, but rather the closest parent that exists on page load.

Here are the docs for on().

jquery .live('click') vs .click()

There might be times when you explicitly want to only assign the click handler to objects which already exist, and handle new objects differently. But more commonly, live doesn't always work. It doesn't work with chained jQuery statements such as:

$(this).children().live('click',doSomething);

It needs a selector to work properly because of the way events bubble up the DOM tree.

Edit: Someone just upvoted this, so obviously people are still looking at it. I should point out that live and bind are both deprecated. You can perform both with .on(), which IMO is a much clearer syntax. To replace bind:

$(selector).on('click', function () {
...
});

and to replace live:

$(document).on('click', selector, function () {
...
});

Instead of using $(document), you can use any jQuery object which contains all the elements you're monitoring the clicks on, but the corresponding element must exist when you call it.



Related Topics



Leave a reply



Submit