I have two divs that are overlapped with two mouse-events. Is it possible to capture both events? I’m only able to capture A or B, but not A and B at the same time.
function adown() {
console.log('A')
}
function bdown() {
console.log('B')
}#a {
pointer-events: all;
width: 200px;
height: 200px;
background: red;
position: absolute;
}
#b {
pointer-events: all;
width: 200px;
height: 200px;
background: blue;
position: absolute;
opacity: 0.5;
top: 50px;
left: 50px;
}<div id="a" onmousedown="adown()"></div> <div id="b" onmousedown="bdown()"></div>
Advertisement
Answer
As mentioned in the comments, you can use document.elementsFromPoints(x,y) where x and y are from mouseposition on the document onclick event. Then, just “filter” the elements by wrapping them up in a div, in this code with id canvas. And lastly, just console.log their id.
As you can see in this snippet:
document.addEventListener("click", function(){
let els = document.elementsFromPoint(event.clientX, event.clientY);
els.forEach(function(el){
if(document.querySelector("#canvas").contains(el)){
console.log(el.id);
}
});
});#A {
pointer-events: all;
width: 200px;
height: 200px;
background:red;
position: absolute;
}
#B {
pointer-events: all;
width: 200px;
height: 200px;
background:blue;
position: absolute;
opacity: 0.5;
top: 50px;
left:50px;
}<div id="canvas"> <div id="A"></div> <div id="B"></div> </div>