Onclick vs addEventListener

Paul Brewczynski picture Paul Brewczynski · Jan 3, 2013 · Viewed 20.8k times · Source

I'm little confusing by using "onclick" "onmousedown" as a property of HTML elements.

Such as:

<button onclick="my_JS_function()"></button>

or

<div onmousedown="my_another_JS_funciton"></div>

But some people tell that only "proper" way of adding "listeners" are by

document.getElementById("my_id").addEventListener("onclick", my_JS_function, false);

What is the more "proper" more supported way of doing that?

Answer

Pranay Rana picture Pranay Rana · Jan 3, 2013

if you already know function and element is part of html i.e. not get added dynamically than its good that you add function inline rather than using extra method call like "addEventListener"

Another thing to note

While onclick works in all browsers, addEventListener does not work in older versions of Internet Explorer, which uses attachEvent instead.

OnClick is a DOM Level 0 property. AddEventListener is part of the DOM Level 2 definition. Read about this : http://www.w3.org/TR/DOM-Level-2-Events/events.html

inline event handlers added as HTML tag attributes, for example:

 <a href="gothere.htm" onlick="alert('Bye!')">Click me!</a> 

The above techniques are simple but have certain disadvantages: they allow you to have just one event handler per element. In addition, with inline event handlers you get very poor separation of JavaScript code from HTML markup.

document.getElementById("my_id").addEventListener("onclick", my_JS_function, false);

Advatange of this : you can add multiple event handler. also separte html and javascript code

For more detail you can read this : Adding an Event Handler