How to trigger only the inner clickable div in a clickable div?
If u click on the inner blue box both inner and outer onclick events getting triggered but I just want to get the blue one triggered?
.outer {
width: 100px;
height: 50px;
cursor: pointer;
background: green;
}
.inner {
width: 50px;
height: 50px;
cursor: pointer;
background: blue;
}
<div class="outer" onclick="alert('Hello world from outside');" role="button" tabIndex="-1">
<div class="inner" onclick="alert('Hello world form inside');" role="button" tabIndex="-1">
</div>
</div>
How to trigger only the inner clickable div in a clickable div?
If u click on the inner blue box both inner and outer onclick events getting triggered but I just want to get the blue one triggered?
.outer {
width: 100px;
height: 50px;
cursor: pointer;
background: green;
}
.inner {
width: 50px;
height: 50px;
cursor: pointer;
background: blue;
}
<div class="outer" onclick="alert('Hello world from outside');" role="button" tabIndex="-1">
<div class="inner" onclick="alert('Hello world form inside');" role="button" tabIndex="-1">
</div>
</div>
Not sure if its necessary to mention but I want to fix this issue in React using sass.
Share Improve this question edited Aug 17, 2017 at 13:20 Mohammad Usman 39.3k20 gold badges98 silver badges99 bronze badges asked Aug 17, 2017 at 13:16 tomoletomole 1,0063 gold badges15 silver badges37 bronze badges 3- 3 Possible duplicate of How to stop event propagation with inline onclick attribute? – Mohammad Usman Commented Aug 17, 2017 at 13:20
- Ohh yes. You are right. Sorry. – tomole Commented Aug 17, 2017 at 13:24
- Found a solution/description fitting your requirements. Link to stackoverflow – Marcel S. Commented Aug 17, 2017 at 13:28
3 Answers
Reset to default 15Use event.stopPropagation();
This method stops the bubbling of an event to parent elements, preventing any parent event handlers from being executed.
<div class="outer" onclick="alert('Hello world from outside');" role="button" tabIndex="-1">
<div class="inner" onclick="alert('Hello world form inside');event.stopPropagation();" role="button" tabIndex="-1">
</div>
</div>
Try This:
function fun(msg) {
alert(msg);
event.stopPropagation();
}
.outer {
width: 100px;
height: 50px;
cursor: pointer;
background: green;
}
.inner {
width: 50px;
height: 50px;
cursor: pointer;
background: blue;
}
<div class="outer" onclick="fun('Hello world from outside');" role="button" tabIndex="-1">
<div class="inner" onclick="fun('Hello world form inside');" role="button" tabIndex="-1">
</div>
</div>
Using
event.target
like this:
html
<div class="_div" data-div="1"><div class="_div" data-div="2"></div></div>
Js
var match = document.querySelectorAll("._div");
for(var i = 0; i <= match.lenght; i++){
match.item(i).addEventListener('click', function(event){
console.log("div clicked:"event.target)
if(event.target.dataset.div == "2"){ // do something ... }
})
}