Skip to content

Instantly share code, notes, and snippets.

@dshster
Forked from jedfoster/javascript.js
Created July 3, 2014 11:43
Show Gist options
  • Save dshster/dabb3850cbbd3213b9bc to your computer and use it in GitHub Desktop.
Save dshster/dabb3850cbbd3213b9bc to your computer and use it in GitHub Desktop.

#Textarea selection and caret manipulation with Javascript

Works is all browsers that support selectionStart.

##Example code

var textarea;
textarea.setCaretPosition(9);
var caretPostion = textarea.getCaretPosition();
textarea.setSelection(0,11);
var selectedText
if (textarea.hasSelection()) {
    selectedText = textarea.getSelectedText();
}

##Real Use Example

Support TAB on a textarea.

HTMLTextAreaElement.prototype.getCaretPosition = function () { //return the caret position of the textarea
return this.selectionStart;
};
HTMLTextAreaElement.prototype.setCaretPosition = function (position) { //change the caret position of the textarea
this.selectionStart = position;
this.selectionEnd = position;
this.focus();
};
HTMLTextAreaElement.prototype.hasSelection = function () { //if the textarea has selection then return true
if (this.selectionStart == this.selectionEnd) {
return false;
} else {
return true;
}
};
HTMLTextAreaElement.prototype.getSelectedText = function () { //return the selection text
return this.value.substring(this.selectionStart, this.selectionEnd);
};
HTMLTextAreaElement.prototype.setSelection = function (start, end) { //change the selection area of the textarea
this.selectionStart = start;
this.selectionEnd = end;
this.focus();
};
HTMLTextAreaElement.prototype.getCaretPosition=function(){return this.selectionStart};HTMLTextAreaElement.prototype.setCaretPosition=function(position){this.selectionStart=position;this.selectionEnd=position;this.focus()};HTMLTextAreaElement.prototype.hasSelection=function(){if(this.selectionStart==this.selectionEnd){return false}else{return true}};HTMLTextAreaElement.prototype.getSelectedText=function(){return this.value.substring(this.selectionStart,this.selectionEnd)};HTMLTextAreaElement.prototype.setSelection=function(start,end){this.selectionStart=start;this.selectionEnd=end;this.focus()};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment