Home >Web Front-end >JS Tutorial >How to Prevent the Cursor from Resetting to the Beginning of a ContentEditable ``?

How to Prevent the Cursor from Resetting to the Beginning of a ContentEditable ``?

Barbara Streisand
Barbara StreisandOriginal
2024-11-10 16:07:021080browse

How to Prevent the Cursor from Resetting to the Beginning of a ContentEditable ``?

Set Cursor Position on ContentEditable

When working with a contentEditable='on'

, it's common to encounter the issue of the cursor resetting to the beginning of the text after regaining focus. To address this, a cross-browser solution has emerged.

Solution:

1. Save Cursor Position:

function saveSelection() {
  if (window.getSelection) { // non-IE
    savedRange = window.getSelection().getRangeAt(0);
  } else if (document.selection) { // IE
    savedRange = document.selection.createRange();
  }
}

This function attaches to the onmouseup and onkeyup events of the

and saves the current selection to the savedRange variable.

2. Restore Cursor Position:

function restoreSelection() {
  if (savedRange != null) {
    if (window.getSelection) { // non-IE
      var s = window.getSelection();
      s.removeAllRanges();
      s.addRange(savedRange);
    } else if (document.createRange) { // non-IE
      window.getSelection().addRange(savedRange);
    } else if (document.selection) { // IE
      savedRange.select();
    }
  }
}

This function attaches to the onfocus event of the

and restores the selection stored in savedRange.

3. Prevent Click Events (Optional):

If you want the cursor to be restored on click instead of resetting to the beginning, you can use the following functions:

var isInFocus = false;

function onDivBlur() {
  isInFocus = false;
}

function cancelEvent(e) {
  if (isInFocus == false && savedRange != null) {
    e.stopPropagation();
    e.preventDefault();
    restoreSelection();
    return false;
  }
}

These functions attach to the onblur, onclick, and onmousedown events and prevent the click event from resetting the cursor position. They also restore the selection, ensuring that the cursor is placed where it left off.

The above is the detailed content of How to Prevent the Cursor from Resetting to the Beginning of a ContentEditable ``?. 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