Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element currently under mouse without using mouse events

WRT building a Firefox Add-on.

Is it possible to get the element under the mouse via some XPCOM or javascript method? (non-js-ctypes please as that requires OS specificity)

I want to detect what is under the mouse when user presses Ctrl + Shift + M.

Right now I'm adding a mouseover listener to the document when the user presses this hotkey, so I can get the element under the mouse when he moves it, but not the element that was under the mouse exactly when he pressed the hotkey combination.

like image 916
Blagoh Avatar asked Jul 02 '14 18:07

Blagoh


People also ask

How do I get current mouse position?

To get the current mouse position we are going to trigger a mouse event. In this case we will use 'mousemove' to log the current X and Y coordinates of the mouse to the console. For a more detailed list of mouse events you could have a read of this.

How do you check if the mouse is over an element?

You can simply use the CSS :hover pseudo-class selector in combination with the jQuery mousemove() to check whether the mouse is over an element or not in jQuery. The jQuery code in the following example will display a hint message on the web page when you place or remove the mouse pointer over the DIV element's box.

How do I find the cursor position in an element?

You can use the jQuery event. pageX and event. pageY in combination with the jQuery offset() method to get the position of mouse pointer relative to an element.


1 Answers

I just looked through the source for code that gets (or stores and makes available) the cursor position. I didn't find anything one could use (from Javascript, XPCOM or not). I might have missed something... MXR is your friend.

However, if you want to avoid mousemove (and this is a good idea in general), you can just look for the innermost hovered element, e.g. like so.

function getInnermostHovered() {
    var n = document.querySelector(":hover");
    var nn;
    while (n) {
        nn = n;
        n = nn.querySelector(":hover");
    }
    return nn;
}

(fiddle demoing the principle)

While this is what I'd consider a hack, it seems to work good enough most of the time, but will fail if the element has mouse events disabled via pointer-events. There could be other issues I didn't think of...

Of course, this can return nothing when the document has no hovered element (e.g. the mouse is not actually within the document).

like image 61
nmaier Avatar answered Oct 31 '22 12:10

nmaier