0

Consider the following code:

<div contenteditable="true">One two th|ree <span>four</span> five six seven</div>

Let's imagine that the caret (bliking cursor) is placed on the word "three", between the letters "h" and "r". What is the best (cross-browser) way to get the positions of the word beginning and end?

My goal is to determine if the caret is closer to the start or end of the word and move caret then to the one that's closer. So for my provided example, it should move the caret to here:

<div contenteditable="true">One two |three <span>four</span> five six seven</div>

I would be best if I could have a cross-browser (including Opera and IE) solution.

ragulka
  • 4,312
  • 7
  • 48
  • 73

1 Answers1

2

You could use the TextRange module of my Rangy library.

Demo: http://jsfiddle.net/8yU2G/

Code:

var editableDiv = document.getElementById("yourDivId");
var sel = rangy.getSelection();
var selRange = sel.getRangeAt(0);
var originalCharRange = selRange.toCharacterRange(editableDiv);
selRange.expand("word");
var expandedCharRange = selRange.toCharacterRange(editableDiv);

// originalCharRange and expandedCharRange have properties "start" and "end"
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thanks, would this be too much trouble without Rangy? I probably do not need all the rest of the functionality from the lib, perhaps I can extract just what I need :) – ragulka Jun 09 '13 at 20:49
  • @ragulka: It depends how complicated your editable DOM can get. You may be able to use functions from here instead: http://stackoverflow.com/questions/13949059/persisting-the-changes-of-range-objects-after-selection-in-html/13950376#13950376 and http://stackoverflow.com/a/16100733/96100 – Tim Down Jun 09 '13 at 22:49