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

How to Get the Word Under the Mouse Cursor with JavaScript?

Patricia Arquette
Release: 2024-10-26 07:06:03
Original
280 people have browsed it

How to Get the Word Under the Mouse Cursor with JavaScript?

How to Retrieve the Word Underneath the Cursor with JavaScript

Determine the word being hovered over by the mouse cursor is an essential task for text-based applications. Suppose you have an HTML page with a paragraph of text:

<code class="html"><p> some long text </p></code>
Copy after login

How can you identify that the cursor is positioned above the word "text"? This article presents a solution that caters specifically to Chrome (and potentially Firefox).

JavaScript Implementation:

<code class="javascript">function getWordAtPoint(elem, x, y) {
  if (elem.nodeType == elem.TEXT_NODE) {
    // Create a range and position it within the element's text content
    var range = elem.ownerDocument.createRange();
    range.selectNodeContents(elem);

    // Initialize position variables
    var currentPos = 0;
    var endPos = range.endOffset;

    // Iterate through the text content
    while (currentPos + 1 < endPos) {
      // Update the range to select a single character
      range.setStart(elem, currentPos);
      range.setEnd(elem, currentPos + 1);

      // Check if the character's bounding rectangle contains the cursor position
      if (
        range.getBoundingClientRect().left <= x &&
        range.getBoundingClientRect().right >= x &&
        range.getBoundingClientRect().top <= y &&
        range.getBoundingClientRect().bottom >= y
      ) {
        // Expand the range to select the word
        range.expand("word");
        var ret = range.toString();
        range.detach();
        return ret;
      }

      // Advance the current position
      currentPos += 1;
    }
  } else {
    // For elements with child nodes (e.g., <p>, <div>), iterate through their children
    for (var i = 0; i < elem.childNodes.length; i++) {
      // Create a range and position it within the child node's text content
      var range = elem.childNodes[i].ownerDocument.createRange();
      range.selectNodeContents(elem.childNodes[i]);

      // Check if the child node's bounding rectangle contains the cursor position
      if (
        range.getBoundingClientRect().left <= x &&
        range.getBoundingClientRect().right >= x &&
        range.getBoundingClientRect().top <= y &&
        range.getBoundingClientRect().bottom >= y
      ) {
        // Recursively call getWordAtPoint on the child node
        range.detach();
        return getWordAtPoint(elem.childNodes[i], x, y);
      } else {
        range.detach();
      }
    }
  }

  return null;
}</code>
Copy after login

Usage:

In the event handler for your mousemove event, you can utilize the getWordAtPoint() function as follows:

<code class="javascript">getWordAtPoint(e.target, e.x, e.y);</code>
Copy after login

The above is the detailed content of How to Get the Word Under the Mouse Cursor 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!