Home >Web Front-end >JS Tutorial >How to Set and Maintain Cursor Position in a ContentEditable Div?

How to Set and Maintain Cursor Position in a ContentEditable Div?

Linda Hamilton
Linda HamiltonOriginal
2024-11-15 03:21:02717browse

How to Set and Maintain Cursor Position in a ContentEditable Div?

Set Cursor Position on contentEditable <div>

When dealing with a contentEditable <div>, default browser functionality resets the cursor position to the beginning of the text upon regaining focus. To resolve this, consider the following solution:

Store and Restore Cursor Position:

  1. Save Current Position: In the onmouseup and onkeyup events, store the current cursor position in a variable, savedRange.
  2. Restore Position: In the onfocus event, restore the saved selection from savedRange.

This approach ensures the cursor is positioned at the last known location when the div regains focus.

Handling Clicks:

To restore the selection upon clicking the div, the following additional steps are necessary:

  1. Cancel Click Events: Attach cancelEvent() to the onclick and onmousedown events. This function prevents the default behavior of these events and calls restoreSelection().
  2. Track Focus State: Use the isInFocus variable to determine whether the div is in focus. Only cancel click events when the div is not in focus.

Working Code:

<div>
var savedRange, isInFocus;

function saveSelection() {
  savedRange = window.getSelection ? window.getSelection().getRangeAt(0) : document.selection.createRange();
}

function restoreSelection() {
  isInFocus = true;
  document.getElementById("area").focus();

  if (savedRange) {
    if (window.getSelection) {
      var s = window.getSelection();
      s.removeAllRanges();
      s.addRange(savedRange);
    } else if (document.createRange) {
      window.getSelection().addRange(savedRange);
    } else if (document.selection) {
      savedRange.select();
    }
  }
}

function onDivBlur() {
  isInFocus = false;
}

function cancelEvent(e) {
  if (isInFocus === false && savedRange) {
    if (e && e.preventDefault) {
      e.stopPropagation();
      e.preventDefault();
    } else {
      window.event.cancelBubble = true;
    }
    restoreSelection();
    return false;
  }
}

The above is the detailed content of How to Set and Maintain Cursor Position in a ContentEditable Div?. 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