2

I am developing an app and speed is a concern. When attaching events to elements there are two ways that I know how to do it:

element.addEventListener('click', function() { // code to execute onclick }) 

or

element.onclick = function() { // code to execute onclick } 

Which way is more efficient and robust? ...even though both work, which is the correct/preferred way?

6
  • element.addEventListener will allow you to add multiple handlers - i suspect onclick calls addEventListener anyway, which would imply addEventListener is your answer. Commented Dec 18, 2014 at 16:50
  • 1
    With addEventListener you can add as many event listeners for an element as you need, while that is impossible with the second method, where if you try to reatach another handler, it will just replace the last attached one. Commented Dec 18, 2014 at 16:51
  • 3
    I feel some Knuth is in order here: "Premature optimisation is the root of all evil" ... In other words, do you have a performance problem, or are you anticipating a problem? If it's the later (which I suspect), you probably want to go with the method that is easiest to read/write, then measure your performance, and if you have a problem, change one thing, and measure again. Do not use guesswork. Commented Dec 18, 2014 at 16:51
  • 1
    Just a sidenote, use references instead of anonymous functions, that way you can remove a listener too. Commented Dec 18, 2014 at 16:54
  • 1
    I recommend to read quirksmode.org/js/introevents.html Commented Dec 18, 2014 at 17:01

1 Answer 1

2

If you want to attach more than one event to your element, you will need to use addEventListener. If not, an inline event will do the trick. In terms of speed there won't be a difference. Please note that

element.onclick = function () { alert('1'); }; element.onclick = function () { alert('2'); }; 

will only alert "2", whilst

element.addEventListener('click', function() {alert('1');} element.addEventListener('click', function() {alert('2');} 

will alert "1" and "2"

as only with addEventListener both events are fired and not overwritten by the later event

element.onclick 

as you wrote it is simply the inline javascript

<button onclick=function() ... 

written in your script part.

as @Teemu commented, setting onclick property doesn't reflect to the HTML, hence an inline handler is not equal to a property

Sign up to request clarification or add additional context in comments.

1 Comment

Notice, that setting onclick property doesn't reflect to the HTML, hence an inline handler is not equal to a property.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.