Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent :hover bubbling [duplicate]

How could hover be prevented for parent element if we hover over it's children?

Here is the code

const parent = document.getElementById('parent')
parent.onmouseover = function testAlert(e) {
  /* alert('parent') */
}
const childRight = document.getElementById('child-right')
childRight.onmouseover = function f(e) {
  e.stopPropagation()
  /* alert('child-right') */
}
const childLeft = document.getElementById('child-left')
childLeft.onmouseenter = function f(e) {
  e.stopPropagation()
  /* alert('child-right') */
}
#parent {
  background: green;
  width: 100px;
  height: 100px;
  position: relative;
  margin: 0 auto;
}

#parent:hover {
  background: rgba(0, 0, 0, 0.8);
}

#child-left {
  background: red;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 0;
  left: -50px;
}

#child-right {
  background: red;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 50px;
  left: 100px;
}
<div id="parent">
  <div id="child-left"></div>
  <div id="child-right"></div>
</div>

https://jsfiddle.net/3tjcsyov/48/

You can see that if you hover over red rects the green one is also hovered if CSS behavior considered. Yes, we can use stopPropagation but it only prevents js handlers execution for parent element while CSS behavior remains unchanged.

like image 436
Igor Chernega Avatar asked Feb 09 '19 07:02

Igor Chernega


1 Answers

If you set the children's pointer-events to none, you can achieve this without any JavaScript.

#parent {
  background: green;
  width: 100px;
  height: 100px;
  position: relative;
  margin: 0 auto;
}

#parent:hover {
  background: rgba(0, 0, 0, 0.8);
}

#child-left {
  background: red;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 0;
  left: -50px;
}

#child-right {
  background: red;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 50px;
  left: 100px;
}

#child-left,
#child-right {
  pointer-events: none;
}
<div id="parent">
  <div id="child-left"></div>
  <div id="child-right"></div>
</div>

https://jsfiddle.net/bepLktoj/

like image 129
Andy Hoffman Avatar answered Sep 27 '22 22:09

Andy Hoffman