Getting the Word Under the Cursor in JavaScript
In web development, it can be useful to know which word the cursor is currently hovering over. This article presents a JavaScript solution that works specifically in Chrome browsers.
Function Overview
The function getWordAtPoint takes three parameters: an element (elem), an x-coordinate (x), and a y-coordinate (y). It uses the Range object to iterate over the text content of an HTML element and determine which word is under the cursor at the specified coordinates.
Implementation
The function first checks if the input element is a text node. If so, it creates a Range object that selects the text content of the element. Then, it uses a loop to incrementally select each character in the text, using the getBoundingClientRect() method to determine if the current character's bounding rectangle contains the specified coordinates. If a match is found, the Range object is expanded to encompass the entire word using the expand() method. Finally, the function returns the string representation of the word.
If the input element is not a text node, the function recursively iterates over its child nodes until it finds the text node containing the specified coordinates.
Usage
To use this function, you can attach it to a mousemove event handler on the desired HTML element. For example:
<code class="javascript">document.addEventListener('mousemove', (e) => { const word = getWordAtPoint(e.target, e.x, e.y); console.log(word); });</code>
This code will log the word under the cursor to the console every time the user moves the mouse over the specified element.
The above is the detailed content of How to Get the Word Under the Cursor in Chrome with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!