Radex Radex - 1 month ago 4
CSS Question

How to catch event on a parent div?

I would like to ask:


  • How to make the group displays OVER the divs a and b?

  • I want to catch event mousedown on group even if a user click on a div a or b.



Basically the group should visually cover the two other divs, so when I click inside the are covered by the group, only group div should detect mousedown.

Notes: I cannot change HTML structure.



document.getElementById('group').addEventListener('click', function(event) {
event.stopPropagation();
alert('click on: ' + event.target.id);
});

#group {
position: absolute;
width: 250px;
height: 250px;
background-color: yellow;
z-index: 2;
opacity: 0.5;
}

#a {
position: absolute;
left: 80px;
width: 50px;
height: 50px;
margin: 10px;
background-color: blue;
z-index: 0;
}

#b {
position: absolute;
width: 50px;
height: 50px;
margin: 10px;
background-color: blue;
z-index: 0;
}

<div id="group">
<div id="a">A</div>
<div id="b">B</div>
</div>




Answer
  1. Use opacity 0 for the children.

  2. Use event.currentTarget instead of event.target.

With this config children are actually above groups, but are not visible and events are cahched by groups elem, not children.

document.getElementById('group').addEventListener('click', function(event) {
  event.stopPropagation();
  alert('click on: ' + event.currentTarget.id);
});
#group {
  position: relative;
  width: 250px;
  height: 250px;
  background-color: yellow;
  z-index: 2;
  opacity: 0.5;
}

#a {
  position: relative;
  left: 80px;
  width: 50px;
  height: 50px;
  margin: 10px;
  background-color: blue;
  z-index: 0;
  opacity: 0
}

#b {
  position: relative;
  width: 50px;
  height: 50px;
  margin: 10px;
  background-color: blue;
  z-index: 0;
  opacity: 0;
}
<div id="group">
  <div id="a">A</div>
  <div id="b">B</div>
</div>