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.
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:
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!