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

How Can I Determine the Start and End Character Offsets of a User Selection Within Its Parent HTML Element?

Susan Sarandon
Release: 2024-11-18 02:44:02
Original
348 people have browsed it

How Can I Determine the Start and End Character Offsets of a User Selection Within Its Parent HTML Element?

Determining the Start and End Offsets of a Range Within Its Parent Container

Problem

Given an HTML element, how can one determine the character offsets within the parent container where a range (user selection) starts and ends, even when the selection spans HTML tags?

Solution

Updated Response:

To obtain both start and end offsets:

function getSelectionCharacterOffsetWithin(element) {
  // Determine start and end offsets
  var start = 0;
  var end = 0;
  // Create ranges
  var range = getRangeAt(0);
  var preCaretRange = range.cloneRange();

  // Set start offset
  preCaretRange.selectNodeContents(element);
  preCaretRange.setEnd(range.startContainer, range.startOffset);
  start = preCaretRange.toString().length;

  // Set end offset
  preCaretRange.setEnd(range.endContainer, range.endOffset);
  end = preCaretRange.toString().length;

  // Return the object
  return { start: start, end: end };
}
Copy after login

Original Response:

The provided code utilizes getSelection() and getRangeAt(0) to retrieve the selection. It then calculates the offset of the caret position within the element using the toString() method on the range. This approach only provides the end offset or caret position.

Example:

function getRangeCharacterOffsetWithin(element) {
  var range, sel;
  if ((sel = window.getSelection())) {
    range = sel.getRangeAt(0);
    range.collapse(false);
    prevRange = range.cloneRange();
    prevRange.selectNodeContents(element);
    prevRange.setEnd(range.endContainer, range.endOffset);
    return prevRange.toString().length;
  }
  return 0;
}
Copy after login

The above is the detailed content of How Can I Determine the Start and End Character Offsets of a User Selection Within Its Parent HTML 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