Home > Web Front-end > JS Tutorial > How Can I Get the Caret Position in a ContentEditable Element?

How Can I Get the Caret Position in a ContentEditable Element?

Susan Sarandon
Release: 2024-11-25 07:10:12
Original
320 people have browsed it

How Can I Get the Caret Position in a ContentEditable Element?

Retrieving the Caret Position in a ContentEditable Element

In contrast to the abundance of solutions for setting the caret position within contentEditable elements, determining its current position has proven elusive for many developers. This question addresses this specific knowledge gap.

To ascertain the caret position within a given contentEditable element upon user input, such as keypresses, one can utilize the following code:

function getCaretPosition(editableDiv) {
  var caretPos = 0,
    sel, range;
  if (window.getSelection) {
    sel = window.getSelection();
    if (sel.rangeCount) {
      range = sel.getRangeAt(0);
      if (range.commonAncestorContainer.parentNode == editableDiv) {
        caretPos = range.endOffset;
      }
    }
  } else if (document.selection && document.selection.createRange) {
    range = document.selection.createRange();
    if (range.parentElement() == editableDiv) {
      var tempEl = document.createElement("span");
      editableDiv.insertBefore(tempEl, editableDiv.firstChild);
      var tempRange = range.duplicate();
      tempRange.moveToElementText(tempEl);
      tempRange.setEndPoint("EndToEnd", range);
      caretPos = tempRange.text.length;
    }
  }
  return caretPos;
}
Copy after login

This code operates under the following assumptions:

  • The editable div contains a single text node without additional nested elements.
  • The CSS white-space property for the editable div is not set to "pre".

For a more comprehensive solution that accommodates more complex content with nested elements, refer to the following Stack Overflow answer: https://stackoverflow.com/a/4812022/96100

The above is the detailed content of How Can I Get the Caret Position in a ContentEditable Element?. 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