Home >Web Front-end >JS Tutorial >How to Keep the Cursor Position in a Content Editable Div After Focus?
Content editable
To address this issue, the following cross-browser solution can be employed:
Step 1: Save Selection
Attach event listeners (onmouseup and onkeyup) to the
Step 2: Restore Selection
Step 2 (a): On Focus
Attach an event listener (onfocus) to the
Step 2 (b): On Click (Optional)
To preserve the selection on click, additional steps are required:
Complete Code (Including Selection Restoration on Click):
<div><pre class="brush:php;toolbar:false">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!