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?

Denis Priebe
  • 2,640
  • 1
  • 23
  • 33
  • `element.addEventListener` will allow you to add multiple handlers - i suspect `onclick` calls `addEventListener` anyway, which would imply `addEventListener` is your answer. – Chris Moutray Dec 18 '14 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. – Chop Dec 18 '14 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. – Martin Tournoij Dec 18 '14 at 16:51
  • [See this question here](http://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick). To you question `addEventListener` or `attachEvent` are often more preferred, but technically both ways are considered correct (considering it is used properly). – Spencer Wieczorek Dec 18 '14 at 16:52
  • 1
    Just a sidenote, use references instead of anonymous functions, that way you can remove a listener too. – Teemu Dec 18 '14 at 16:54
  • 1
    I recommend to read http://quirksmode.org/js/introevents.html – Felix Kling Dec 18 '14 at 17:01

1 Answers1

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

baao
  • 71,625
  • 17
  • 143
  • 203
  • 2
    Notice, that setting `onclick` property doesn't reflect to the HTML, hence an inline handler is not equal to a property. – Teemu Dec 18 '14 at 16:58