Webistrate - Draw Your Own Conclusions

JavaScript: Set Cursor Position of textarea

Posted by Jamie Munro | February 13, 2012 |

Share

Probably not required often, but you just never know when you might need to set the cursor position inside a textarea tag that you have on your website.  Perhaps you want to add a button that will insert some text before the current cursor position and set the cursor back to where the user left it afterwards.  In the following example, I will create some basic functions to allow you to set where the cursor goes inside of a textarea.

 Let’s dive right into the core JavaScript code:

function setSelectionRange(input, selectionStart, selectionEnd) {
if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
else if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
}
}

function setCaretToPos (input, pos) {
setSelectionRange(input, pos, pos);
}

To execute the code, it would be done as follows:

setCaretToPos(document.getElementById("testinput"), 8);

So, assuming you have a textarea with the id of testinput created on your page, the cursor position will be set after the 8th character in the textarea.

The above code could then be updated to use the equivalent getSelectionRange of the textarea when a user clicks a button, insert your code, then move the cursor to the end of the newly inserted code.

Summary

By using the setSelectionRange or the createTextRange, it will allow you to set the mouse cursor position of a form element item such as a textarea, input box, etc…

Share


Random Posts

Leave a Reply

You must be logged in to post a comment.

Buy one of my books