Home >Web Front-end >JS Tutorial >How to Get the Word Under the Cursor in JavaScript?

How to Get the Word Under the Cursor in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 17:28:02389browse

How to Get the Word Under the Cursor in JavaScript?

Getting the Word under the Cursor in JavaScript

Determining the word currently under the cursor in an HTML document is a common requirement for text manipulation applications. This article explores a reliable method to achieve this using JavaScript, specifically in the context of modern browsers like Chrome.

To determine the word under the cursor, we leverage the capabilities of the DOM's Range object. This approach iterates over the text content of the element and identifies the word that encompasses the cursor's position based on its boundingClientRect.

The JavaScript function provided in the answer, getWordAtPoint(), takes three parameters: the element, the x-coordinate of the cursor, and the y-coordinate of the cursor. It recursively iterates through the element's child nodes, expanding the search if the cursor is within the bounding rectangle of a text node. Once it encounters a match, it returns the identified word.

In the event that the cursor is not positioned over any text content, the function returns null. This can be incorporated into a mousemove event handler to dynamically determine the word under the cursor as the user moves the mouse over the text.

The above is the detailed content of How to Get the Word Under the Cursor in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn