2

I don't actually want to trigger an event. I just want to find out programmatically which element will handle the onmousedown if the mouse is clicked at position x/y.

The purpose is to then add an interceptor to that element which point-event: none

1
  • event.target directly gives the clicked item. .... Commented Aug 25, 2021 at 2:32

1 Answer 1

3
// without pointer-events: none;
const element = document.elementFromPoint(mouseX, mouseY);
function elementsFromPoint(x, y) { // pointer-events: none;
    const elements = document.body.getElementsByTagName("*");
    var elementsList = Array.prototype.slice.call(elements);

    var results = []
    elementsList.forEach(element => {
        var rect = element.getBoundingClientRect();

        if (rect.left < x && x < rect.right && rect.top < y && y < rect.bottom) {
            results.push(element)
        }
    });
    return results;
}
window.addEventListener('load', () => {
    const textarea = document.querySelector('#text')
    document.addEventListener('click', (e) => {

        const element = elementsFromPoint(e.clientX, e.clientY);
        console.log(element)
    })

})
Sign up to request clarification or add additional context in comments.

8 Comments

Does this take into account specialties like "pointer-events: none"?
this is working with pointer-events: none
Yeah that's exactly what I want. From the docs of elementFromPoint: "Elements with pointer-events set to none will be ignored, and the element below it will be returned."
This is a great answer, I'll accept it for the time being. :)
"We can use mouse move event instead of mouse click" Could you explain this maybe? It's confusing me @MERN Thanks for your help
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.