When setup like this, clicking on a label that has a child button triggers button's onclick event:
function fireButton() {
console.log("Button fired!");
}
<label>Label
<button onclick="fireButton()">Button</button>
</label>
When setup like this, clicking on a label that has a child button triggers button's onclick event:
function fireButton() {
console.log("Button fired!");
}
<label>Label
<button onclick="fireButton()">Button</button>
</label>
is there a way to prevent this?
Share Improve this question asked Nov 12, 2020 at 11:49 Guga FigueiredoGuga Figueiredo 2925 silver badges19 bronze badges 2- 2 That is just a pattern you should avoid to begin with; mon accessibility guidelines explicitly advise against nesting such interactive elements which have their own functionality into labels. – C3roe Commented Nov 12, 2020 at 11:57
- 1 granted.. I'll work on a better design in the future. – Guga Figueiredo Commented Nov 12, 2020 at 12:21
5 Answers
Reset to default 3You can add preventDefault for labels and keep the existing code:
document.querySelector("label").addEventListener("click", function(event) {
event.preventDefault();
}, false);
Add for attribute to label.
function fireButton() {
console.log("Button fired!");
}
<label for=''>Label
<button onclick="fireButton()">Button</button>
</label>
You can put the button outside the label
<label>Label</label>
<button onclick="fireButton()">Button</button>
You could use a different tag e.g <span>
rather than the label
But if you really need to use the <label>
, you should prevent the default behaviour of the label onclick()
like so:
function fireButton(){
//add actions here
}
function preventDefault(event){
event.preventDefault()
}
<label onclick="preventDefault(event)">Label
<button onclick="fireButton()">Button</button>
</label>
Here's an approach in CSS which also disables triggering button
's :active
state when clicking on label
. Overriding label
's onClick
event does not do that.
label {
pointer-events: none;
}
button {
pointer-events: initial;
}