Eric Freeman
Eric Freeman

Reputation: 82

how do i trigger onMouseEnter for elements behind other elements

I'm trying to trigger mouseEnter event when mouse is on top of multiple elements.

I want both mouseEnter events to trigger when the mouse is at the center, and preferably for both to turn yellow.

Run the code snippet below for an example:

<!DOCTYPE html>
<html>
<head>
<style>
div:hover {
  background-color: yellow;
}
div {
  width: 100px;
  height:100px;
  background:green;
  border: 2px solid black;
}
.second {
  transform:translateX(50%) translateY(-50%);
}
</style>
<script>
  function onhover(){console.log('hovered')}
</script>
</head>
<body>

<div onmouseenter=onhover()></div>
<div onmouseenter=onhover() class='second'></div>

</body>
</html>

Upvotes: 4

Views: 1584

Answers (4)

Stephane Vanraes
Stephane Vanraes

Reputation: 16451

The problem is that elements are blocking the mouse such that elements in the background do not receive the event. With the exception that events bubble to the parent.

Given that you could change your markup slightly to get this effect.

First add a class to your boxes so we can easily find them in JavaScript:

<div class="box"></div>
<div class="box second"></div>

Then adapt the CSS such that this background change is toggled with a class instead:

.box.hovered {
  background-color: yellow;
}

And then the JavaScript:

// Get all box elements
const boxes = document.querySelectorAll('.box');

boxes.forEach(box => {
  // For each box attach a listener to when the mouse moves
  box.addEventListener('mousemove', (ev) => {
    // Get the position of the mouse
    const { x, y } = ev;
    boxes.forEach(b => {
      // for each box get it's dimension and location
      const rect = b.getBoundingClientRect();
      // check if the pointed is in the box
      const flag = x > rect.left && x < rect.right && y > rect.top && y < rect.bottom;
      // toggle the class
      b.classList.toggle('hovered', flag);
    });
  });
});

This can be improved a lot, especially if you have more boxes by getting the rectangles beforehand and then using the index in the forEach to link the box to it's rectangle:

const boxes = document.querySelectorAll('.box');
const rects = [...boxes].map(box => box.getBoundingClientRect());

Another improvement is to use the fact that events bubble to the parent, that means you could wrap all boxes in one parent and only add a listener to this parent.

Upvotes: 0

Aaron Meese
Aaron Meese

Reputation: 2233

According to MDN, the mouseenter event does not bubble, whereas the mouseover event does. However, even if it DID bubble, your elements currently have no relation to one another, thus the mouse events are captured by the upper element.

One possible way around this is with the amazing elementsFromPoint function in JavaScript, which makes quick work of solving your issue:

// Only the IDs of the elments you are interested in
const elems = ["1", "2"];

// Modified from https://stackoverflow.com/a/71268477/6456163
window.onload = function() {
  this.addEventListener("mousemove", checkMousePosition);
};

function checkMousePosition(e) {
  // All the elements the mouse is currently overlapping with
  const _overlapped = document.elementsFromPoint(e.pageX, e.pageY);

  // Check to see if any element id matches an id in elems
  const _included = _overlapped.filter((el) => elems.includes(el.id));
  const ids = _included.map((el) => el.id);

  for (const index in elems) {
    const id = elems[index];
    const elem = document.getElementById(id);

    if (ids.includes(id)) {
      elem.style.background = "yellow";
    } else {
      elem.style.background = "green";
    }
  }
}
div {
  width: 100px;
  height: 100px;
  background: green;
  border: 2px solid black;
}
.second {
  transform: translateX(50%) translateY(-50%);
}
<div id="1"></div>
<div id="2" class="second"></div>

Upvotes: 3

Edoldin
Edoldin

Reputation: 160

I think that you can not without javascript, and with it it's a bit tricky, you have to check on every mousemove if the coordinates of the mouse are in de bounding box of the element, this fill fail with elements with border radius but for the others it's ok

<script>


var hovered=[]
function addHover(element){hovered.push(element)}

function onhover(element){console.log("hovered",element)}

function onCustomHover(e){
    hovered.forEach((el,i)=>{
        let bounds=el.getBoundingClientRect()
        if (e.pageX > bounds.left && e.pageX < bounds.bottom  &&
            e.pageY > bounds.top && e.pageY < bounds.right ) {            
            onhover(i);
        }
    })
}


</script>
</head>
<body>

<div id="div1"></div>
<div id="div2" class='second'></div>
<script>
    document.body.addEventListener('mousemove', onCustomHover, true);//{capture :false});
    addHover(document.getElementById("div1"))
    addHover(document.getElementById("div2"));
</script>

I would appreciate if you could rate the answer if that was usefull to you because I can not make comments yet <3

Upvotes: 1

vladys.bo
vladys.bo

Reputation: 740

It will be easier to change your code a little bit.

ex. Add to your div elements class box. Add to your styles class with name hovered which will look like:

.hovered {
  background-color: yellow;
}

Into JS(between script tag) add event listeners (code not tested, but idea is shown), also move script to place before closing body tag:

const boxes = document.querySelectorAll('.box');

boxes.forEach(box => {
  box.addEventListener('mouseover', () => {
    boxes.forEach(b => b.classList.add('hovered'));
  });

  box.addEventListener('mouseout', () => {
    boxes.forEach(b => b.classList.remove('hovered'));
  });
});

Upvotes: 0

Related Questions