Home >Web Front-end >JS Tutorial >How to Set and Maintain Cursor Position in a 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:
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:
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!