Is there a way to mouseenter event layerd elements?

Viewed 58

Let's say I have 2 circles one over the other (intersecting), is there a way to have them both access mouseover, mouseenter, and mouseleave? I want them to stay independent from each other, but when the cursor goes over both they should both change color.

If my cursor is only over red circle, then only red should change, and if my cursor is on blue then only blue should change. If my cursor is on both (intersection) then both should change color. These circles will be moving so I don't want a static solution for the intersection.

I know pointer-events: none; will remove the functionality allowing me to access the lower layer, but I want them to both be active.

CIRCLE.addEventListener('mouseenter', changeColorOnTouch, false);
CIRCLE2.addEventListener('mouseenter', changeColorOnTouch2, false);


CIRCLE.addEventListener('mouseleave', function(){CIRCLE.removeAttribute("style");}, false);
CIRCLE2.addEventListener('mouseleave', function(){CIRCLE2.removeAttribute("style");}, false);

https://jsfiddle.net/hrxp2cm4/48/

2 Answers

Add a parent div and on its hover change CSS of children.

.container:hover > .circle {
  background: #f55;
}
.container:hover > .circle2 {
  background: #5ff;
}
.circle {
  position: absolute;
  top: 25px;
  left: 25px;
  width: 100px;
  height: 100px;
  color: transparent;
  border: 2px solid red;
  border-radius: 50%;
  z-index: 5;
}

.circle2 {
  position: absolute;
  top: 0px;
  width: 100px;
  height: 100px;
  color: transparent;
  border: 2px solid blue;
  border-radius: 50%;
}
<div class="container">
  <div class="circle"></div>
  <div class="circle2"></div>
</div>

When the mouse is in the inner Circle, the mouse is still in the outer circle, themouseleave would not trigger. You can't do it like that, there is a workaround however, you can manually set the color of the outer circle on the mouseenter for the inner circle.

here is the code

const c1 = document.getElementById('c1') // default color red
const c2 = document.getElementById('c2') // default color blue

c1.addEventListener('mouseenter', () => c1.style.background = 'black')
c2.addEventListener('mouseenter', () => {
  c1.style.background = 'red'
  c2.style.background = 'white'
})

c1.addEventListener('mouseleave', () => c1.style.background = 'red')
c2.addEventListener('mouseleave', () => {
  c1.style.background = 'black'
  c2.style.background = 'blue' 
})
Related