Introduction

The HTML textarea tag can be challenging to deal with. Each browser has it's own way of handling things like cursor manipulation and string insertion. Luckily most of the issues are solvable. In this brief article we look at 5 different functions that solve the various issues you may run into when dealing with the textarea tag. Note that all of these examples require jQuery, though you could in theory modify these functions to run without jQuery.

setSelection

The setSelection function selects a block of text in your text area.


jQuery.fn.extend({
	setSelection: function(selectionStart, selectionEnd) {
		    if(this.length == 0) return this;
		    input = this[0];

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

		    return this;
		}
})

For example, let's say you have the sentence My favorite dog is a hound dog. if you want to select the text My fa you would do:


$("#mytextarea").setSelection(0,5);

setCursorPosition

The setCursorPosition function set's the cursor's position within the text to whatever you want:


jQuery.fn.extend({
	setCursorPosition: function(position){
	    if(this.length == 0) return this;
	    return $(this).setSelection(position, position);
	}
})

For example, the following line of code would place the cursor at position 5 within your text area:


$("#mytextarea").setCursorPosition(5)

Note that setCursorPosition requires setSelection.

focusEnd

This one is pretty simple, this uses setCursorPosition to position the cursor at the end of the text.


jQuery.fn.extend({
	focusEnd: function(){
		this.setCursorPosition(this.val().length);
		return this;
	}
})

For example, the following line of text would place the cursor at the end of the text in the text area:


$("#mytextarea").focusEnd()

getCursorPosition

This function gets the cursor's current position.


jQuery.fn.extend({
	getCursorPosition: function() {
	        var el = $(this).get(0);
	        var pos = 0;
	        if('selectionStart' in el) {
	            pos = el.selectionStart;
	        } else if('selection' in document) {
	            el.focus();
	            var Sel = document.selection.createRange();
	            var SelLength = document.selection.createRange().text.length;
	            Sel.moveStart('character', -el.value.length);
	            pos = Sel.text.length - SelLength;
	        }
	        return pos;
	    }
})

For example, if your cursor was in position 5 of the text area, the following line of code would return 5:


pos = $("#mytextarea").getCursorPosition();

insertAtCursor

Finally, we have insertAtCursor. insertAtCursor inserts the text at the location of the cursor.


jQuery.fn.extend({
	insertAtCursor: function(myValue) {
		return this.each(function(i) {
			if (document.selection) {
				//For browsers like Internet Explorer
				this.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
				this.focus();
			}
			else if (this.selectionStart || this.selectionStart == '0') {
				//For browsers like Firefox and Webkit based
				var startPos = this.selectionStart;
				var endPos = this.selectionEnd;
				var scrollTop = this.scrollTop;
				this.value = this.value.substring(0, startPos) + myValue + 
						    this.value.substring(endPos,this.value.length);
				this.focus();
				this.selectionStart = startPos + myValue.length;
				this.selectionEnd = startPos + myValue.length;
				this.scrollTop = scrollTop;
			} else {
				this.value += myValue;
				this.focus();
			}
		})
	}
})

For example, to insert world! after the word 'Hello' in your text area, you would do this:


$("#mytextarea").setCursorPosition(5);
$("#mytextarea").insertAtCursor(" world!");

Complete Listing

The complete listing of all functions combined can be found below.


jQuery.fn.extend({
	setCursorPosition: function(position){
		if(this.length == 0) return this;
		return $(this).setSelection(position, position);
	},

	setSelection: function(selectionStart, selectionEnd) {
		if(this.length == 0) return this;
		input = this[0];

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

		return this;
	},

	focusEnd: function(){
		this.setCursorPosition(this.val().length);
		return this;
	},

	getCursorPosition: function() {
		var el = $(this).get(0);
		var pos = 0;
		if('selectionStart' in el) {
			pos = el.selectionStart;
		} else if('selection' in document) {
			el.focus();
			var Sel = document.selection.createRange();
			var SelLength = document.selection.createRange().text.length;
			Sel.moveStart('character', -el.value.length);
			pos = Sel.text.length - SelLength;
		}
		return pos;
	},

	insertAtCursor: function(myValue) {
		return this.each(function(i) {
			if (document.selection) {
			  //For browsers like Internet Explorer
			  this.focus();
			  sel = document.selection.createRange();
			  sel.text = myValue;
			  this.focus();
			}
			else if (this.selectionStart || this.selectionStart == '0') {
			  //For browsers like Firefox and Webkit based
			  var startPos = this.selectionStart;
			  var endPos = this.selectionEnd;
			  var scrollTop = this.scrollTop;
			  this.value = this.value.substring(0, startPos) + myValue + 
							this.value.substring(endPos,this.value.length);
			  this.focus();
			  this.selectionStart = startPos + myValue.length;
			  this.selectionEnd = startPos + myValue.length;
			  this.scrollTop = scrollTop;
			} else {
			  this.value += myValue;
			  this.focus();
			}
	  	})
	}
})

If you'd like to play with these functions more, I've put them on jsfiddle. That's it, thanks for reading!