1

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.

Mehmed
  • 2,880
  • 4
  • 41
  • 62
  • Related http://stackoverflow.com/q/6249095 , some of your code seems to be from answers there, your problem is probably due to what you're trying to calculate as "position"; `focusOffset` is not the value you want. Maybe you want `element.textContent.length`. – Paul S. Sep 13 '13 at 01:03
  • Well, when I use `range.setStart(element.firstNode, 5)` it works... But I have problem in getting the position where double click end as you said. – Mehmed Sep 13 '13 at 01:13
  • Read a bit more about ranges. For each range boundary, the offset is relative to the deepest node containing the boundary. – Tim Down Sep 13 '13 at 09:20
  • Maybe it is better to set cursor to the beginning rather than trying to put it mouse pointer whereabouts after double click on the span. What do you think? – Mehmed Sep 13 '13 at 09:34

1 Answers1

0

A similar problem and its solution is here, I am surprised for finding it in the second day of search considering my offensive search yesterday. Any better solution is welcomed, since even this one cannot bypass text selection at first double click.

Community
  • 1
  • 1
Mehmed
  • 2,880
  • 4
  • 41
  • 62