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>
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>
If you use document.elementsFromPoints from previous answers and use an attribute to describe which function you want to call on click you'd be able to fire two function with one click.
const functions = {
funcA: () => console.log('A'),
funcB: () => console.log('B'),
}
document.addEventListener("click", e => {
const elements = document.elementsFromPoint(e.clientX, e.clientY);
elements.forEach(el => {
if(document.querySelector("#container").contains(el)){
const functionAttribute = el.getAttribute('data-function');
if(functionAttribute && functionAttribute.length && functions[functionAttribute]){
functions[functionAttribute]();
}
}
});
});
.elem {
width: 200px;
height: 200px;
background-color: red;
position: absolute;
}
<html>
<body>
<div id="container">
<div data-function="funcA" class="elem">A</div>
<div data-function="funcB" class="elem">B</div>
</div>
</body>
</html>
Or you can assign both divs the same class and then iterate over them:
<div class="test"></div>
<div class="test"></div>
const testDivs = document.querySelectorAll('.test');
testDivs.forEach(testDiv => {
testDiv.addEventListener('click', () => {
// do something...
});
});