Home  >  Article  >  Web Front-end  >  How to Determine the Word Under the Cursor in JavaScript?

How to Determine the Word Under the Cursor in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 17:27:02941browse

How to Determine the Word Under the Cursor in JavaScript?

Determining the Word Under the Cursor in JavaScript

Problem:

Given an HTML page containing text, how can you determine the word that the cursor is currently hovering over?

Solution:

For Browsers that Support Shadow DOM (e.g., Chrome)

<code class="js">function getWordAtPoint(elem, x, y) {
  if (elem.nodeType === elem.TEXT_NODE) {
    // Create a range encompassing the element and determine offsets
    let range = elem.ownerDocument.createRange();
    range.selectNodeContents(elem);
    let currentPos = 0;
    let endPos = range.endOffset;

    // Iterate through the characters until finding the one under the cursor
    while (currentPos + 1 < endPos) {
      range.setStart(elem, currentPos);
      range.setEnd(elem, currentPos + 1);
      let boundingClientRect = range.getBoundingClientRect();

      if (
        boundingClientRect.left <= x &&
        boundingClientRect.right >= x &&
        boundingClientRect.top <= y &&
        boundingClientRect.bottom >= y
      ) {
        // Expand to word boundaries and return the text
        range.expand("word");
        let result = range.toString();
        range.detach();
        return result;
      }

      currentPos += 1;
    }
  } else {
    // Recursively check child nodes
    for (let i = 0; i < elem.childNodes.length; i++) {
      range = elem.childNodes[i].ownerDocument.createRange();
      range.selectNodeContents(elem.childNodes[i]);

      // Check if child node is under the cursor
      if (
        range.getBoundingClientRect().left <= x &&
        range.getBoundingClientRect().right >= x &&
        range.getBoundingClientRect().top <= y &&
        range.getBoundingClientRect().bottom >= y
      ) {
        range.detach();
        // Recursively search the child node
        return getWordAtPoint(elem.childNodes[i], x, y);
      } else {
        range.detach();
      }
    }
  }

  return null;
}</code>

Example Usage:

<code class="js">document.addEventListener("mousemove", (e) => {
  let word = getWordAtPoint(e.target, e.x, e.y);
  console.log("Word under cursor:", word);
});</code>

The above is the detailed content of How to Determine 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