I'm looking to wrap a cursor in span
tags in a contenteditable div
.
Example (cursor represented by |
):
The fox jumps |
The fox jumps <span>|</span>
Any attempt to modify the innerHTML results in the cursor being moved to the end of the line. I'd like it to be inserted in between the new HTML span
's.
This isn't possible cross-browser because of implementation issues. Attempting to place the caret within an empty inline element such as a <span>
in both WebKit and IE will actually place the caret immediately before the element. The following demonstrates this: it will do you what you expect in Firefox but not WebKit or IE.
http://jsfiddle.net/8TTb3/1/
You can use a DOM Range and the Selection API to insert elements at the caret position, except in IE < 9 which does not support these and instead has its own API.
Code:
var range = sel.getRangeAt(0);
var span = document.createElement("span");
range.insertNode(span);
range.setStart(span, 0);
range.setEnd(span, 0);
sel.removeAllRanges();
sel.addRange(range);
Actually, you can do a trick:
var range = sel.getRangeAt(0);
var span = document.createElement("span");
span.innerHTML = "​";
range.insertNode(span);
range.setStart(span, 0);
range.setEnd(span, 1);
sel.removeAllRanges();
sel.addRange(range);
works in chrome: http://jsfiddle.net/8TTb3/8/
The only thing you can control is the position of the cursor in the (already parsed) contents of the div. If you put a span in there it will be parsed before the cursor is inserted by the browser, at which point the cursor will be either before it or after it.
So no, I don't think this is possible.