jong shin
jong shin

Reputation: 794

Allow mouse event propagation on overlapped divs with absolute position

I have two divs in a container, and these divs have the absolute position. The problem is that I need to handle mousemove events for both divs, but when they are overlapped each other, mousemove events for the div behind another div are not fired. How can I make it so that mousemove events are fired for both divs?

The code below is just to demonstrate the problem. Actual application has many absoluate position html elements and I need to find which elements are hit by the current mouse cursor. In other words, I cannot manually fire mousemove events, because the purpose of using mousemove event is to find which html elements are hit by the current mouse cursor, not the opposite. And I know I can manually calculate it from the container mousemove event handler, but like I said, I have many html elements, and I do not want to iterate through all the html elements, calculate and find the html elements hit by the current cursor.

<!DOCTYPE html>
<html>
<head>
<style>
#container {
   border: 3px solid #73AD21;
   height: 300px;
   width: 300px;
}
#log{
   height: 200px;
   overflow-y: scroll;
}
#div1{
   position: absolute;
   left: 100px;
   top: 100px;
   height: 100px;
   width: 100px;
   border: 3px solid red;
}
#div2{
   position: absolute;
   left: 100px;
   top: 100px;
   height: 100px;
   width: 100px;
   border: 3px solid yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" ></script>
<script>
$( document ).ready(function() {
   document.getElementById("div1").addEventListener('mousemove',function( event ) {
    var msg = "div1 handler for .mousemove() called at ";
    msg += event.pageX + ", " + event.pageY;
    $( "#log" ).append( "<div>" + msg + "</div>" );
   });
   document.getElementById("div2").addEventListener('mousemove',function( event ) {
    var msg = "div2 handler for .mousemove() called at ";
    msg += event.pageX + ", " + event.pageY;
    $( "#log" ).append( "<div>" + msg + "</div>" );
   });
});

</script>
</head>
<body>

<div id="container">
  <div id="div1"></div>
  <div id="div2"></div>
</div>
<div id="log" >
</div>
</body>
</html>

Upvotes: 3

Views: 738

Answers (1)

Josef Wittmann
Josef Wittmann

Reputation: 1349

Have a look at elementsFromPoint().

And since it it's experimental, have a look at a polyfill, too.

Upvotes: 1

Related Questions