Home >Web Front-end >JS Tutorial >How to Keep the Cursor Position in a Content Editable Div After Focus?

How to Keep the Cursor Position in a Content Editable Div After Focus?

DDD
DDDOriginal
2024-11-10 00:37:02551browse

How to Keep the Cursor Position in a Content Editable Div After Focus?

Setting Cursor Position on ContentEditable <div>

Problem:

Content editable <div> elements tend to reset the cursor position to the beginning of the text every time focus is regained. This can be undesirable when the cursor needs to be restored to its previous position.

Solution:

To address this issue, the following cross-browser solution can be employed:

Step 1: Save Selection

Attach event listeners (onmouseup and onkeyup) to the <div> to capture the current cursor position (savedRange) when the mouse button is released or a key is released.

Step 2: Restore Selection

Step 2 (a): On Focus

Attach an event listener (onfocus) to the <div> that restores the previously saved selection.

Step 2 (b): On Click (Optional)

To preserve the selection on click, additional steps are required:

  • Register onclick and onmousedown event listeners that cancel the click event (cancelEvent()).
  • Inside cancelEvent(), restore the saved selection and set isInFocus to true.
  • On blur (onblur), set isInFocus to false.

Complete Code (Including Selection Restoration on Click):

<div>
var savedRange, isInFocus;

function saveSelection() {
  // ... (Selection saving logic as described in Step 1)
}

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

  if (savedRange != null) {
    // ... (Selection restoration logic as described in Step 2)
  }
}

function onDivBlur() {
  isInFocus = false;
}

function cancelEvent(e) {
  if (isInFocus === false && savedRange != null) {
    // ... (Event cancellation logic as described in Step 2 (b))
  }
}

The above is the detailed content of How to Keep the Cursor Position in a Content Editable Div After Focus?. 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