0

I was just about to set onclick event for my element in javascript, but I wonder which of these two options is more efficient:

document.getElementById(myid).onclick = function(e){...}

or

document.body.onclick = function(e){if(e.target.id == myid)...}

Is there any difference? Is one of these declarations processed slower?

  • Efficient in what sense? The second takes more time to type, so its less efficient in that sense. – TJHeuvel Sep 09 '14 at 15:51
  • The first is faster....you are zeroing in on the ID of interest plus there is no conditional statement to detect the ID like in option #2 – The One and Only ChemistryBlob Sep 09 '14 at 15:52
  • @TheOneandOnlyChemistryBlob can you prove this in a test? – TJHeuvel Sep 09 '14 at 15:53
  • Sure...go ahead and use jsperf... – The One and Only ChemistryBlob Sep 09 '14 at 15:54
  • 1
    @SaintLouisFella it's good to keep efficiency in mind because in the long run you will create code where you (as jQuery says) "write less, do more" but just remember that TJHeuvel is correct and the gains you get from these microoptimizations will be very very small....for big speed gains, minimize queries, use descendant selectors, use css whenever possible, and more – The One and Only ChemistryBlob Sep 09 '14 at 15:58
  • One is directly binding the event handler, the other is using *event delegation*. Both ways have the (dis)advantages. I'm pretty sure this was covered extensively, so just google for it. E.g. http://stackoverflow.com/q/8827430/218196 – Felix Kling Sep 09 '14 at 16:25

2 Answers2

1

Its recommended that you use AddEventListener instead of binding to OnClick.

As for efficiency i'm not sure what you are worrying about. If its performance you should measure your issues and solve those instead of wondering about possibly minute details.

TJHeuvel
  • 12,403
  • 4
  • 37
  • 46
1

If you use document.body.onclick = function(e){if(e.target.id == myid)...} you are listening to ALL the click of the mouse, include buttons, links, ecc ecc. This could slow down your site (expecially on mobile device or old computers).

Use document.getElementById(myid).onclick = function(e){...} isn't bad, but I suggest you to use document.getElementById('...').addEventListener("event", function(event) {...});