Onclick vs addEventListener

21,081

Solution 1

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

Solution 2

The latter (addEventListener()) is the best way, as you can attach multiple events of the same type to the same element.

By assigning to onclick, etc, you will overwrite existing handlers.

Share:
21,081
Paul Brewczynski
Author by

Paul Brewczynski

Looking for a job.

Updated on January 22, 2020

Comments

  • Paul Brewczynski
    Paul Brewczynski over 4 years

    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?

  • Paul Brewczynski
    Paul Brewczynski over 11 years
    But I can do a function which call other functions... to circumvent the problem of "onclick".
  • anam
    anam almost 11 years
    @alex in jquery addEventListener() gives error , Uncaught TypeError: Object [object Object] has no method 'addEventListener' ?? what to do?
  • user3167101
    user3167101 almost 11 years
    @simmisimmi If you have a question, you can ask it.
  • Schien
    Schien over 10 years
    and when debugging or maintaining such app, its handler is logically associated with the button, as it's declared inline. In this case, inline declaration makes implementation and maintenance easy. There's no need to figure out whether there're other events attached to it. Please explain again, in this scenario, what's the advantage of separating html and javascript?