Home > Web Front-end > JS Tutorial > body text

How to Get the Word Under the Cursor in Chrome with JavaScript?

Barbara Streisand
Release: 2024-10-24 18:01:02
Original
185 people have browsed it

How to Get the Word Under the Cursor in Chrome with JavaScript?

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!