'Should the event listener be placed on the container or on the individual buttons?
I'm wondering what is the best practise on where to attach JavaScript click listeners.
i.e. Should the event listener be placed on the container or on the individual buttons?
e.g.
Example html:
<div id="content">
somecontent blah blaoh
<button class="button1"></button>
<button class="button2"></button>
blah blah blah
<table></table>
more content...
</div>
- If I put the click listener on the
#content, then the event will fire when I click on anything within that div. So then in the event handler, I can look at the class of the clicked target and perform the correct behaviour. - Or should I attach the event listener on the
.button1and .button2directly?
What are the pros and cons etc.?
Solution 1:[1]
My simplified answer we look like this
<div id="container1" onClick="doAction1()">
<button id="A" class="buttonA" onClick="doActionA()"></button>
<button id="B" class="buttonB" onClick="doActionB()"></button>
</div>
Shortly, I'll use container for my buttons A and B just in case I need to fire same common to both event, and will set their local events directly. Inspection of mix-in events isn't convenient, at least to me.
Solution 2:[2]
If you want to perform different actions when .button1 and .button2 are clicked assign separate event handlers to each button to avoid having to inspect the target. If your performing the same action when either button is clicked you could assign the event handler to the div however at this point you really need to question why you have two buttons.
Solution 3:[3]
Attach it to the buttons directly. Pros:
- it is much easier
- everybody uses it
- you don't need to put in the extra code that checks the button that was clicked
- there is no reason not to
nobody applies the event handlers on the parent. I see no reason to do so and have never seen any code which does that and it has never crossed my mind to do it.
one little suggestion, however: have ids on the buttons instead of classes, as it will be easier to add event handlers to them.
if you have a more specific problem or have a reason to use an event handler on the parent, put it in a comment.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Panayot Karabakalov |
| Solution 2 | Kevin Bowersox |
| Solution 3 | markasoftware |
