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
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
- many matching elements would create many identical handlers and thus increase memory footprint
- 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");
Difference between .on('click') and .off('click').on('click')
This adds a new click
event handler:
$('#link').on('click', function(){});
This removes all existing click
event handlers that were attached with .on()
(if any) and then adds a new click
event handler:
$('#link').off('click').on('click', function(){});
Difference between jQuery's .on('click') vs .click()
.click()
is an alias of .trigger('click')
, while .click(data, fn)
is an alias of .on('click', null, data, fn)
.
You might not pass in a second argument, in which case, .on('click', null, data, fn)
will still bind the handler using data
as the handler instead of fn
.
Additionally, what this means is that there's no way to assign a delegate via .click(...)
, so if you need event delegation you should use .on(...)
From the latest source:
jQuery v1.10.2, lines 7554-7564:jQuery.each( ("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").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
Difference between `$(document).on(click, a` and `$(a).click(`
$(document).on("click", "a", function () {
will bind the event on the a
elements which are not present at the time of binding event. This is called as event delegation.
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
Whereas $("a").click(function () {
will bind events only to the a
elements which are present in DOM.
Related Topics
Can Scripts Be Inserted With Innerhtml
Why Can't I Call a Function Named Clear from an Onclick Attribute
In What Situations Would Ajax Long/Short Polling Be Preferred Over Html5 Websockets
Maximum Size of a ≪Canvas≫ Element
How to Scroll to an Element Inside a Div
Should Setting an Image Src to Data Url Be Available Immediately
Losing Scope When Using Ng-Include
How to Include Multiple Js Files Using Jquery $.Getscript() Method
How to Add/Remove Several Classes in One Single Instruction With Classlist
Creating a Textarea With Auto-Resize
Convert Json Data to a HTML Table
Reading File Contents on the Client-Side in JavaScript in Various Browsers
How to Calculate the Number of Days Between Two Dates
Electron Require() Is Not Defined
(Html) Download a Pdf File Instead of Opening Them in Browser When Clicked