0

I have two different divs that they call different functions when you click on them. The div that has the class="msg1" calls a function called message1() that brings one alert saying('this is message 1'). This is working well

My problem is that I have another div called class="msg2" that it is inside of the the div class="msg1" and when I click on this div class="msg2" it calls the function message2() AND ALSO the function message1(), which I don't want.

When I click on the div class="msg2" I JUST want to call the function message2(). How can I just execute the function message2() when I click on the div class=msg2?

const message1 = () => {
  alert('this is message 1')
}

const message2 = () => {
  alert('this is message 2')
}
.msg1 {
  width: 600px;
  height: 600px;
  background-color: darkgoldenrod;
  display: flex;
  align-items: center;
  justify-content: center;
}

.msg2 {
  width: 300px;
  height: 300px;
  background-color: dimgrey;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="msg1" onclick="message1()">
  <div class="msg2" onclick="message2()">
  </div>
</div>
j08691
  • 204,283
  • 31
  • 260
  • 272
Denis Ximenes
  • 351
  • 3
  • 12

1 Answers1

1

You can stop the propagation of the event from the child div using event.stopPropagation()

const message1 = (event) => {
  alert('this is message 1')
}

const message2 = (event) => {
  alert('this is message 2');
  event.stopPropagation();
}
.msg1 {
  width: 600px;
  height: 600px;
  background-color: darkgoldenrod;
  display: flex;
  align-items: center;
  justify-content: center;
}

.msg2 {
  width: 300px;
  height: 300px;
  background-color: dimgrey;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div class="msg1" onclick="message1(event)">
  <div class="msg2" onclick="message2(event)">
  </div>
</div>
brk
  • 48,835
  • 10
  • 56
  • 78