4

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>

enter image description here

Not sure if its necessary to mention but I want to fix this issue in React using sass.

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
tomole
  • 927
  • 3
  • 12
  • 35
  • 3
    Possible duplicate of [How to stop event propagation with inline onclick attribute?](https://stackoverflow.com/questions/387736/how-to-stop-event-propagation-with-inline-onclick-attribute) – Mohammad Usman Aug 17 '17 at 13:20
  • Ohh yes. You are right. Sorry. – tomole Aug 17 '17 at 13:24
  • Found a solution/description fitting your requirements. [Link to stackoverflow](https://stackoverflow.com/questions/34725592/link-within-a-link-onclick-event-avoid-both-click-events-triggering/34725912) – Marcel S. Aug 17 '17 at 13:28

3 Answers3

15

Use 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>
Yashwardhan Pauranik
  • 5,370
  • 5
  • 42
  • 65
1

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>
Ehsan
  • 12,655
  • 3
  • 25
  • 44
0

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 ... }
  })
}
Miller Mosquera
  • 119
  • 4
  • 14