Skip to content
Advertisement

Js event inside an other js event mobile device

I’m wondering how to handle an event inside an other one

Here is the code I use:

var title=document.getElementsByClassName('lv1');
for (var i = 0; i < title.length; i++) {
      title[i].addEventListener('click',  (event) => {
      alert("click title");
},false);
}
var deleted=document.getElementsByClassName('remove');
for (var i = 0; i < deleted.length; i++) {
  deleted[i].addEventListener('click',  (event) => {
    alert("click remove");
  },false);
}
<div class="lv1">
  <h1>
    test
  </h1>
  <button class="remove">
  REMOVE
  </button>
</div>

You have two click events lv1 and delete. But delete is inside lv1, so when I go for delete, both click events are triggered.

On computer, I can fix this by adding a mouseover event to know if I’m hovering the delete or not and this way I know if the lv1 event must be triggered or not.

But I can’t use this trick with mobile device; the mouseover event didn’t exist. Did I miss something?

Advertisement

Answer

You need event.stopPropagation()

var title=document.getElementsByClassName('lv1');
for (var i = 0; i < title.length; i++) {
      title[i].addEventListener('click',  (event) => {
      alert("click title");
},false);
}
var deleted=document.getElementsByClassName('remove');
for (var i = 0; i < deleted.length; i++) {
  deleted[i].addEventListener('click',  (event) => {
    alert("click remove");
    event.stopPropagation();
  },false);
}
<div class="lv1">
  <h1>
    test
  </h1>
  <button class="remove">
  REMOVE
  </button>
</div>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement