I am attempting to create a simple texteditor with HTML5 contenteditable on a div tag. As you know, selected text is handled quite differently in IE.
this.retrieveAnchorNode = function() {
var anchorNode;
if (document.selection)
anchorNode = document.selection.createRange().parentElement();
else if (document.getSelection)
anchorNode = window.getSelection().anchorNode;
}
I am looking for a way to get the selected textnode (not the text itself), like I can do with "anchorNode" and "focusNode" on other browsers. The only alternative on IE I have found is the "parentElement()" function, which only manages to select the contenteditable div itself.
Any ideas?
Here's my version of the function you need from IERange, with my comments:
My answer is derived from Tim Down' solution. Thanks a lot to Tim!
However, there's two problems with Tim's solution when working on IE. (1) the offset as calculated is incorrect, and (2) too complex, lots of code.
See my demonstration below.
For problem 1, if you click somewhere at about the last line of the text, for example somewhere in "shoulder pork loin shankle turducken shank cow. Bacon ball tip sirloin ham.", you can notice the offset calculation is different with IE (original solution) and IE method 2 (my solution). Also, the results from IE method 2 (my solution) and from Chrome, Firefox are the same.
My solution is also much simpler. The trick is, after use TextRange to make selection at the absolute X/Y position, get a type of IHTMLSelection by calling document.getSelection(). This does not work for IE<9 but if that's OK for you, this method is much simpler. Another caveat is, with IE the method's side effect (same as the original method) is change of selection (i.e. losing user's original selection).
Your best bet for this at the moment is IERange. This library will return you a DOM Range-like object in IE, with the selection provided in terms of nodes and offsets.
I have come up with a solution. It isn't perfect, but it's able to select the element containing the text node (most often
p
,h1
etc.). We can get the position of the selection with the TextRange functiongetBoundingClientRect()
, and withdocument.elementFromPoint(x, y)
we are able to get the element containing the text. Example:If anyone has a better solution, please share it.