Move cursor position with javascript?

I want to move the carriage exactly four spaces in front of its current position so that I can insert the tab correctly. I already have the HTML insert at the carriage position, but when I insert the HTML, the carriage is left behind. I spent the last hour or so looking at various ways to do this, and I tried a lot of them, but I can't get any of them to work for me. Here is the most recent method I tried:

function moveCaret(input, distance) { if(input.setSelectionRange) { input.focus(); input.setSelectionRange(distance, distance); } else if(input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd(distance); range.moveStart(distance); range.select(); } } 

He does nothing - does not move the carriage, does not throw any errors or anything else. It puzzles me. And yes, I know that the above method (presumably) should set the carriage at a certain position from the beginning of the specified node (i.e. input ), but even this does not work. So what exactly am I doing wrong, and how can I do it right?


Edit: based on links that ov provided that I managed to combine something, which finally does something: error. Hooray! Here's the new code:

 this.moveCaret = function(distance) { if(that.win.getSelection) { var range = that.win.getSelection().getRangeAt(0); range.setStart(range.startOffset + distance); } else if (that.win.document.selection) { var range = that.win.document.selection.createRange(); range.setStart(range.startOffset + distance); } } 

This now gives the Uncaught Error: NOT_FOUND_ERR: DOM Exception 8 error. Any ideas why?

+7
source share
1 answer

The code snippet has text inputs and text fields, not contenteditable .

Provided that all your content is in the same node text, and the choice is completely contained within it, the following will work in all major browsers, including IE 6.

Demo: http://jsfiddle.net/9sdrZ/

the 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)); } } else if ( (sel = win.document.selection) ) { // IE <= 8 if (sel.type != "Control") { range = sel.createRange(); range.move("character", charCount); range.select(); } } } 
+18
source

All Articles