Get DOM element under cursor


#1

Hello,

I’m trying to find a way to get the DOM element that is under the blinking cursor(s) to be able to use it as a target for a tooltip. Is there any way to achieve that ?

Thansk,
Regards,
Peekmo


#2

Something like this should work:

document.body.addEventListener 'mousemove', (e) ->
  # e.target is the element that triggered the event

Note that you won’t be able to access elements that are part of a shadow DOM that way, and elements with pointer-events: none won’t trigger any events neither.


#3

Thank you,

But I’m interested in the blinking cursor position, not the mouse sorry, it wasn’t clear.


#4

I completely missed this method before, but there’s a elementFromPoint method on document and elements that should help you on that:

e = atom.workspace.getActiveTextEditor()
v = atom.views.getView(e)
{top, left} = v.pixelPositionForScreenPosition(e.getLastCursor().getScreenPosition())

v.shadowRoot.elementFromPoint(left,top)

Get cursor's pixel position relatively to editor's viewport
#5

I discovered this method too this morning, but… v.shadowRoot.elementFromPoint(left,top)always returns null

I’m not sure that the shadow dom can returns elements with that method ? Or perhaps something is missing…
pixelPositionForScreenPosition returns top & left positions correctly


#6

Here’s a demonstration that it works as expected:

Edit: In this example I don’t compensate for the editor offset and scrolling, so using the coordinates returned by pixelPositionForScreenPosition might return a null element.


#7

Ok, the problem is somewhere else so. Thank you very much