Skip to content

Pointer events

All the syntax highlighted code in an editor has pointer-events: none. Therefore all pointer events are being handled by the editor’s underlying <textarea> element. This makes it difficult to add any hover or click functionality to the editor’s tokens. This guide will showcase some utilities that make this easier.

When adding pointer event handlers to the textarea itself, the event target will be the textarea. To obtain the token element or line the pointer is currently on, use the addPointerListener() function. It supports pointermove, pointerdown, pointerup, mousemove, mousedown, mouseup, and click events and returns a cleanup function that removes the listener.

The example below uses addPointerListener() to add a data-hover attribute to the token the pointer is on.

Below, the editorHoverDescriptions() extension has been used to display a tooltip with a CSS selector for the token along with its position in the editor computed by getTokenOffset().

The following styles are added to the tooltip and hovered tokens:

The hover and tooltip functionality from this example are added to all editors on this page in case you want to try it.

Computing the token at the pointer’s location is done with document.elementsFromPoint(), which requires changing the pointer-events property of the line the pointer is on. This can be expensive for lines with lots of elements. If this causes any issues, a filter function that receives the line, line number, and event can be passed to both addPointerListener() and editorHoverDescriptions(). If this filter returns false, then computing the target and running the listener is skipped.