I am after a definitive, cross-browser solution to set the cursor/caret position to the last known position when a contentEditable='on' <div> regains focus. It appears default functionality of a content editable div is to move the caret/cursor to the beginning of the text in the div each time you click on it, which is undesirable.
I believe I would have to store in a variable the current cursor position when they are leaving focus of the div, and then re-set this when they have focus inside again, but I have not been able to put together, or find a working code sample yet.
If anybody has any thoughts, working code snippets or samples I'd be happy to see them.
I don't really have any code yet but here is what I do have:
<script type="text/javascript">
// jQuery
$(document).ready(function() {
$('#area').focus(function() { .. } // focus I would imagine I need.
}
</script>
<div id="area" contentEditable="true"></div>
PS. I have tried this resource but it appears it does not work for a <div>. Perhaps only for textarea (How to move cursor to end of contenteditable entity)
Best Answer
This solution works in all major browsers:
saveSelection()
is attached to theonmouseup
andonkeyup
events of the div and saves the selection to the variablesavedRange
.restoreSelection()
is attached to theonfocus
event of the div and reselects the selection saved insavedRange
.This works perfectly unless you want the selection to be restored when the user clicks the div aswell (which is a bit unintuitative as normally you expect the cursor to go where you click but code included for completeness)
To achieve this the
onclick
andonmousedown
events are canceled by the functioncancelEvent()
which is a cross browser function to cancel the event. ThecancelEvent()
function also runs therestoreSelection()
function because as the click event is cancelled the div doesn't receive focus and therefore nothing is selected at all unless this functions is run.The variable
isInFocus
stores whether it is in focus and is changed to "false"onblur
and "true"onfocus
. This allows click events to be cancelled only if the div is not in focus (otherwise you would not be able to change the selection at all).If you wish to the selection to be change when the div is focused by a click, and not restore the selection
onclick
(and only when focus is given to the element programtically usingdocument.getElementById("area").focus();
or similar then simply remove theonclick
andonmousedown
events. Theonblur
event and theonDivBlur()
andcancelEvent()
functions can also safely be removed in these circumstances.This code should work if dropped directly into the body of an html page if you want to test it quickly: