Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get screenX for DOM element in Javascript

Tags:

javascript

dom

When I listen for mouseover on an element, I get an event fired that has screenX, clientX, pageX and lots of other nice details about where the mouse is relative to the screen and relative to the element that fired the event.

If I just call element.mouseover(), my handler runs, but the mouse location and other properties are all null. I looked at initMouseEvent, but it requires you specify screenX which I don't know.

My question is, how can I get these values without the mouse being over the element or even in the window at all?

like image 326
powlette Avatar asked Aug 15 '26 13:08

powlette


1 Answers

In Javascript:

function getScreenCoords(element) {
    let rect = element.getBoundingClientRect();
    return {
            x: window.screenX + rect.left,
            y: window.screenY + rect.top
        }
}
like image 100
Jared Landers Avatar answered Aug 17 '26 02:08

Jared Landers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!