I have a span, it becomes editable after double clicking on it. However, some text is selected due to double click and I remove that selection using this code:
function removeSelectedText(element) {
if (window.getSelection || document.getSelection) {
oSelection = (window.getSelection ? window:document).getSelection();
oSelection.removeAllRanges();
} else {
document.selection.empty();
}
}
After this operation, now-editable non-selected span loses focus. All I want to move the caret to the last clicked place in the span. I try the code below but didn't work ('element' is span itself):
...
var selection = (window.getSelection ? window:document).getSelection();
var position = selection.getRangeAt(0).focusOffset;
element.focus();
var range = document.createRange();
range.setStart(element, position);
range.setEnd(element, position);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
I try whatever I found but couldn't get it working. I can't focus it anymore due to frustration. That would be awesome if you help me...
UPDATE: In range.setStart()
and range.setEnd()
, element.firstChild
should be used instead of element
.