Reputation: 369
I have this code:
<div style="width:200px;height:100px;border:solid 1px" onclick="alert(1)">
Title
<br />
Subtitle
<div style="float:right">
<input type="checkbox" />
</div>
</div>
I want to redirect the user to a url when he clicks on the div (where the alert is now) but I want to allow the user with functionality when he clicks on the checkbox.
Is it possible to allow the checkbox to be clicked and change status without invoking the alert(1)
from the div below ?
Upvotes: 3
Views: 1714
Reputation: 32145
You will need to use stopPropagation()
method on the checkbox
click event handler, so the click of the checkbox won't trigger the click of its parents divs:
HTML:
<input type="checkbox" onclick="avoidAlert(event)" />
JS:
function avoidAlert(event) {
event.stopPropagation();
}
function avoidAlert(event) {
event.stopPropagation();
}
<div style="width:200px;height:100px;border:solid 1px" onclick="alert(1)">
Title
<br /> Subtitle
<div style="float:right">
<input type="checkbox" onclick="avoidAlert(event)" />
</div>
</div>
MDN Ref for stopPropagation()
method:
The
stopPropagation()
method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases.
Upvotes: 1
Reputation: 4147
You could either try event.stopPropagation()
inside an extra event handler on the checkbox, or simply check inside the div's event handler if the target of the click has been the checkbox:
var theDiv = document.querySelector('.outer'),
theCheckbox = document.querySelector('input');
theDiv.addEventListener('click', divClicked);
function divClicked(e) {
if (e.target !== theCheckbox) {
alert('You clicked the div!');
}
}
<div class="outer" style="width:200px;height:100px;border:solid 1px">
Title
<br />
Subtitle
<div style="float:right">
<input type="checkbox" />
</div>
</div>
Upvotes: 0
Reputation: 1213
You need to use event.stopPropagation(); function. This function prevents further propagation of the current event in the capturing and bubbling phases.
<div style="width:200px;height:100px;border:solid 1px" onclick="alert(1)">
Title
<br />
Subtitle
<div style="float:right">
<input type="checkbox" onclick="onCheckBoxCicked(event)"/>
</div>
function onCheckBoxCicked(event) {
alert(2)
event.stopPropagation();
};
Upvotes: 6