Skip to content

Type Editor


Type Editor / @type-editor/selection-util / caret-from-point / caretFromPoint

Function: caretFromPoint()

ts
function caretFromPoint(
  doc,
  x,
  y,
): {
  node: Node;
  offset: number;
};

Defined in: caret-from-point.ts:31

Gets the caret position from a point in the document.

This function tries browser-specific methods to determine the DOM position (node and offset) at the given screen coordinates. It handles both Firefox's caretPositionFromPoint and Chrome/Safari's caretRangeFromPoint.

The offset is clipped to the node size to handle edge cases where browsers might return invalid offsets (e.g., text offsets into <input> nodes).

Parameters

ParameterTypeDescription
docDocumentThe document to query
xnumberThe X coordinate in viewport space
ynumberThe Y coordinate in viewport space

Returns

ts
{
  node: Node;
  offset: number;
}

An object containing the node and offset at the point, or undefined if not found

NameTypeDefined in
nodeNodecaret-from-point.ts:33
offsetnumbercaret-from-point.ts:33

Example

typescript
const position = caretFromPoint(document, event.clientX, event.clientY);
if (position) {
  console.log("Caret is at:", position.node, position.offset);
}