Move The Cursor Position With Javascript?
I'm looking to move the caret exactly four spaces ahead of its current position so that I can insert a tab properly. I've already got the HTML insertion at the caret's position wor
Solution 1:
The code snippet you have is for text inputs and textareas, not contenteditable
elements.
Provided that all your content is in a single text node and the selection is completely contained within it, the following will work in all major browsers, including IE 6.
Demo: http://jsfiddle.net/9sdrZ/
Code:
function moveCaret(win, charCount) {
var sel, range;
if (win.getSelection) {
// IE9+ and other browsers
sel = win.getSelection();
if (sel.rangeCount > 0) {
var textNode = sel.focusNode;
var newOffset = sel.focusOffset + charCount;
sel.collapse(textNode, Math.min(textNode.length, newOffset));
}
} elseif ( (sel = win.document.selection) ) {
// IE <= 8if (sel.type != "Control") {
range = sel.createRange();
range.move("character", charCount);
range.select();
}
}
}
Post a Comment for "Move The Cursor Position With Javascript?"