What's the difference between addEventListener
and onclick
?
var h = document.getElementById("a");
h.onclick = dothing1;
h.addEventListener("click", dothing2);
The code above resides together in a separate .js file, and they both work perfectly.
This question is related to
javascript
onclick
addeventlistener
In this answer I will describe the three methods of defining DOM event handlers.
element.addEventListener()
Code example:
const element = document.querySelector('a');_x000D_
element.addEventListener('click', event => event.preventDefault(), true);
_x000D_
<a href="//google.com">Try clicking this link.</a>
_x000D_
element.addEventListener()
has multiple advantages:
element.removeEventListener()
.useCapture
parameter, which indicates whether you'd like to handle event in its capturing or bubbling phase. See: Unable to understand useCapture attribute in addEventListener..onevent
properties of DOM elements, lots of inexperienced JavaScript programmers thinks that the event name is for example onclick
or onload
. on
is not a part of event name. Correct event names are click
and load
, and that's how event names are passed to .addEventListener()
.element.onevent = function() {}
(e.g. onclick
, onload
)Code example:
const element = document.querySelector('a');_x000D_
element.onclick = event => event.preventDefault();
_x000D_
<a href="//google.com">Try clicking this link.</a>
_x000D_
This was a way to register event handlers in DOM 0. It's now discouraged, because it:
onevent
property back to its initial state (i.e. null
).window.onload
, for example: window.onload = "test";
, it won't throw any errors. Your code wouldn't work and it would be really hard to find out why. .addEventListener()
however, would throw error (at least in Firefox): TypeError: Argument 2 of EventTarget.addEventListener is not an object.onevent
HTML attribute)Code example:
<a href="//google.com" onclick="event.preventDefault();">Try clicking this link.</a>
_x000D_
Similarly to element.onevent
, it's now discouraged. Besides the issues that element.onevent
has, it:
Content-Security-Policy
HTTP header to block inline scripts and allow external scripts only from trusted domains. See How does Content Security Policy work?The difference you could see if you had another couple of functions:
var h = document.getElementById('a');
h.onclick = doThing_1;
h.onclick = doThing_2;
h.addEventListener('click', doThing_3);
h.addEventListener('click', doThing_4);
Functions 2, 3 and 4 work, but 1 does not. This is because addEventListener
does not overwrite existing event handlers, whereas onclick
overrides any existing onclick = fn
event handlers.
The other significant difference, of course, is that onclick
will always work, whereas addEventListener
does not work in Internet Explorer before version 9. You can use the analogous attachEvent
(which has slightly different syntax) in IE <9.
onclick is basically an addEventListener that specifically performs a function when the element is clicked. So, useful when you have a button that does simple operations, like a calculator button. addEventlistener can be used for a multitude of things like performing an operation when DOM or all content is loaded, akin to window.onload but with more control.
Note, You can actually use more than one event with inline, or at least by using onclick by seperating each function with a semi-colon, like this....
I wouldn't write a function with inline, as you could potentially have problems later and it would be messy imo. Just use it to call functions already done in your script file.
Which one you use I suppose would depend on what you want. addEventListener for complex operations and onclick for simple. I've seen some projects not attach a specific one to elements and would instead implement a more global eventlistener that would determine if a tap was on a button and perform certain tasks depending on what was pressed. Imo that could potentially lead to problems I'd think, and albeit small, probably, a resource waste if that eventlistener had to handle each and every click
One detail hasn't been noted yet: modern desktop browsers consider different button presses to be "clicks" for AddEventListener('click'
and onclick
by default.
onclick
and AddEventListener
click fire on left and middle click.onclick
fires only on left click, but AddEventListener
click fires on left, middle and right clicks.Also, middle-click behavior is very inconsistent across browsers when scroll cursors are involved:
It is also worth noting that "click" events for any keyboard-selectable HTML element such as input
also fire on space or enter when the element is selected.
Using inline handlers is incompatible with Content Security Policy so the addEventListener
approach is more secure from that point of view. Of course you can enable the inline handlers with unsafe-inline
but, as the name suggests, it's not safe as it brings back the whole hordes of JavaScript exploits that CSP prevents.
Javascript tends to blend everything into objects and that can make it confusing. All into one is the JavaScript way.
Essentially onclick is a HTML attribute. Conversely addEventListener is a method on the DOM object representing a HTML element.
In JavaScript objects, a method is merely a property that has a function as a value and that works against the object it is attached to (using this for example).
In JavaScript as HTML element represented by DOM will have it's attributes mapped onto its properties.
This is where people get confused because JavaScript melds everything into a single container or namespace with no layer of indirection.
In a normal OO layout (which does at least merge the namespace of properties/methods) you would might have something like:
domElement.addEventListener // Object(Method)
domElement.attributes.onload // Object(Property(Object(Property(String))))
There are variations like it could use a getter/setter for onload or HashMap for attributes but ultimately that's how it would look. JavaScript eliminated that layer of indirection at the expect of knowing what's what among other things. It merged domElement and attributes together.
Barring compatibility you should as a best practice use addEventListener. As other answers talk about the differences in that regard rather than the fundamental programmatic differences I will forgo it. Essentially, in an ideal world you're really only meant to use on* from HTML but in an even more ideal world you shouldn't be doing anything like that from HTML.
Why is it dominant today? It's quicker to write, easier to learn and tends to just work.
The whole point of onload in HTML is to give access to the addEventListener method or functionality in the first place. By using it in JS you're going through HTML when you could be applying it directly.
Hypothetically you can make your own attributes:
$('[myclick]').each(function(i, v) {
v.addEventListener('click', function() {
eval(v.myclick); // eval($(v).attr('myclick'));
});
});
What JS does with is a bit different to that.
You can equate it to something like (for every element created):
element.addEventListener('click', function() {
switch(typeof element.onclick) {
case 'string':eval(element.onclick);break;
case 'function':element.onclick();break;
}
});
The actual implementation details will likely differ with a range of subtle variations making the two slightly different in some cases but that's the gist of it.
It's arguably a compatibility hack that you can pin a function to an on attribute since by default attributes are all strings.
If you are not too worried about browser support, there is a way to rebind the 'this' reference in the function called by the event. It will normally point to the element that generated the event when the function is executed, which is not always what you want. The tricky part is to at the same time be able to remove the very same event listener, as shown in this example: http://jsfiddle.net/roenbaeck/vBYu3/
/*
Testing that the function returned from bind is rereferenceable,
such that it can be added and removed as an event listener.
*/
function MyImportantCalloutToYou(message, otherMessage) {
// the following is necessary as calling bind again does
// not return the same function, so instead we replace the
// original function with the one bound to this instance
this.swap = this.swap.bind(this);
this.element = document.createElement('div');
this.element.addEventListener('click', this.swap, false);
document.body.appendChild(this.element);
}
MyImportantCalloutToYou.prototype = {
element: null,
swap: function() {
// now this function can be properly removed
this.element.removeEventListener('click', this.swap, false);
}
}
The code above works well in Chrome, and there's probably some shim around making "bind" compatible with other browsers.
addEventListener
lets you set multiple handlers, but isn't supported in IE8 or lower.
IE does have attachEvent
, but it's not exactly the same.
element.onclick = function() { /* do stuff */ }
element.addEventListener('click', function(){ /* do stuff */ },false);
They apparently do the same thing: listen for the click event and execute a callback function. Nevertheless, they’re not equivalent. If you ever need to choose between the two, this could help you to figure out which one is the best for you.
The main difference is that onclick is just a property, and like all object properties, if you write on more than once, it will be overwritten. With addEventListener() instead, we can simply bind an event handler to the element, and we can call it each time we need it without being worried of any overwritten properties. Example is shown here,
Try it: https://jsfiddle.net/fjets5z4/5/
In first place I was tempted to keep using onclick, because it’s shorter and looks simpler… and in fact it is. But I don’t recommend using it anymore. It’s just like using inline JavaScript. Using something like – that’s inline JavaScript – is highly discouraged nowadays (inline CSS is discouraged too, but that’s another topic).
However, the addEventListener() function, despite it’s the standard, just doesn’t work in old browsers (Internet Explorer below version 9), and this is another big difference. If you need to support these ancient browsers, you should follow the onclick way. But you could also use jQuery (or one of its alternatives): it basically simplifies your work and reduces the differences between browsers, therefore can save you a lot of time.
var clickEvent = document.getElementByID("onclick-eg");
var EventListener = document.getElementByID("addEventListener-eg");
clickEvent.onclick = function(){
window.alert("1 is not called")
}
clickEvent.onclick = function(){
window.alert("1 is not called, 2 is called")
}
EventListener.addEventListener("click",function(){
window.alert("1 is called")
})
EventListener.addEventListener("click",function(){
window.alert("2 is also called")
})
The context referenced by 'this'
keyword in JavasSript is different.
look at the following code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<input id="btnSubmit" type="button" value="Submit" />
<script>
function disable() {
this.disabled = true;
}
var btnSubmit = document.getElementById('btnSubmit');
btnSubmit.onclick = disable();
//btnSubmit.addEventListener('click', disable, false);
</script>
</body>
</html>
What it does is really simple. when you click the button, the button will be disabled automatically.
First when you try to hook up the events in this way button.onclick = function(),
onclick event will be triggered by clicking the button, however, the button will not be disabled because there's no explicit binding between button.onclick and onclick event handler. If you debug see the 'this'
object, you can see it refers to 'window'
object.
Secondly, if you comment btnSubmit.onclick = disable();
and uncomment
//btnSubmit.addEventListener('click', disable, false);
you can see that the button is disabled because with this way there's explicit binding between button.onclick event and onclick event handler. If you debug into disable function, you can see 'this'
refers to the button control
rather than the window
.
This is something I don't like about JavaScript which is inconsistency.
Btw, if you are using jQuery($('#btnSubmit').on('click', disable);
), it uses explicit binding.
As far as I know, the DOM "load" event still does only work very limited. That means it'll only fire for the window object
, images
and <script>
elements for instance. The same goes for the direct onload
assignment. There is no technical difference between those two. Probably .onload =
has a better cross-browser availabilty.
However, you cannot assign a load event
to a <div>
or <span>
element or whatnot.
According to MDN, the difference is as below:
addEventListener:
The EventTarget.addEventListener() method adds the specified EventListener-compatible object to the list of event listeners for the specified event type on the EventTarget on which it's called. The event target may be an Element in a document, the Document itself, a Window, or any other object that supports events (such as XMLHttpRequest).
onclick:
The onclick property returns the click event handler code on the current element. When using the click event to trigger an action, also consider adding this same action to the keydown event, to allow the use of that same action by people who don't use a mouse or a touch screen. Syntax element.onclick = functionRef; where functionRef is a function - often a name of a function declared elsewhere or a function expression. See "JavaScript Guide:Functions" for details.
There is also a syntax difference in use as you see in the below codes:
addEventListener:
// Function to change the content of t2
function modifyText() {
var t2 = document.getElementById("t2");
if (t2.firstChild.nodeValue == "three") {
t2.firstChild.nodeValue = "two";
} else {
t2.firstChild.nodeValue = "three";
}
}
// add event listener to table
var el = document.getElementById("outside");
el.addEventListener("click", modifyText, false);
onclick:
function initElement() {
var p = document.getElementById("foo");
// NOTE: showAlert(); or showAlert(param); will NOT work here.
// Must be a reference to a function name, not a function call.
p.onclick = showAlert;
};
function showAlert(event) {
alert("onclick Event detected!");
}
`let element = document.queryselector('id or classname');
element.addeventlistiner('click',()=>{
do work })`
<button onclick="click()">click</click>
function click(){ do work };
An element can have only one event handler attached per event type, but can have multiple event listeners.
So, how does it look in action?
Only the last event handler assigned gets run:
const btn = document.querySelector(".btn")
button.onclick = () => {
console.log("Hello World");
};
button.onclick = () => {
console.log("How are you?");
};
button.click() // "Hello World"
All event listeners will be triggered:
const btn = document.querySelector(".btn")
button.addEventListener("click", event => {
console.log("Hello World");
})
button.addEventListener("click", event => {
console.log("How are you?");
})
button.click()
// "Hello World"
// "How are you?"
IE Note: attachEvent
is no longer supported. Starting with IE 11, use addEventListener
: docs.
While onclick
works in all browsers, addEventListener
does not work in older versions of Internet Explorer, which uses attachEvent
instead.
The downside of onclick
is that there can only be one event handler, while the other two will fire all registered callbacks.
addEventListener
can add multiple events, whereas with onclick
this cannot be done.onclick
can be added as an HTML
attribute, whereas an addEventListener
can only be added within <script>
elements.addEventListener
can take a third argument which can stop the event propagation.Both can be used to handle events. However, addEventListener
should be the preferred choice since it can do everything onclick
does and more. Don't use inline onclick
as HTML attributes as this mixes up the javascript and the HTML which is a bad practice. It makes the code less maintainable.
It should also be possible to either extend the listener by prototyping it (if we have a reference to it and its not an anonymous function) -or make the onclick
call a call to a function library (a function calling other functions).
Like:
elm.onclick = myFunctionList;
function myFunctionList(){
myFunc1();
myFunc2();
}
This means we never have to change the onclick
call just alter the function myFunctionList()
to do whatever we want, but this leaves us without control of bubbling/catching phases so should be avoided for newer browsers.
Source: Stackoverflow.com