Return to Snippet

Revision: 5236
at February 21, 2008 07:27 by arunpjohny


Initial Code
<html>
	<head>
<title>Get/Set Caret in Textarea Example</title>
		<script>
function doGetCaretPosition (ctrl) {

	var CaretPos = 0;
	// IE Support
	if (document.selection) {

		ctrl.focus ();
		var Sel = document.selection.createRange ();

		Sel.moveStart ('character', -ctrl.value.length);

		CaretPos = Sel.text.length;
	}
	// Firefox support
	else if (ctrl.selectionStart || ctrl.selectionStart == '0')
		CaretPos = ctrl.selectionStart;

	return (CaretPos);

}


function setCaretPosition(ctrl, pos)
{

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

function process()
{
	var no = document.getElementById('no').value;
	setCaretPosition(document.getElementById('get'),no);
}

		</script>
	</head>
	<body>
		<textarea id="get" name="get" rows="5" cols="31">Please write some integer in the textbox given below and press "Set Position" button. Press "Get Position" button to get the position of cursor.</textarea>
		<br>

		Enter Caret Position: <input type="text" id="no" size="1" /><input type="button" onclick="process();" value="Set Position">
		<BR>
		<input type="button" onclick="alert(doGetCaretPosition(document.getElementById('get')));"
			value="Get Position">
	</body>
</html>

Initial URL
http://demo.vishalon.net/getset.htm

Initial Description
I got this code from http://blog.vishalon.net/Post/57.aspx


The actual two methods required are

function doGetCaretPosition (ctrl) {
	var CaretPos = 0;
	// IE Support
	if (document.selection) {
		ctrl.focus ();
		var Sel = document.selection.createRange ();
		Sel.moveStart ('character', -ctrl.value.length);
		CaretPos = Sel.text.length;
	}
	// Firefox support
	else if (ctrl.selectionStart || ctrl.selectionStart == '0')
		CaretPos = ctrl.selectionStart;
	return (CaretPos);
}

function setCaretPosition(ctrl, pos)
{
	if(ctrl.setSelectionRange)
	{
		ctrl.focus();
		ctrl.setSelectionRange(pos,pos);
	}
	else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}

Initial Title
Get/set Cursor In Html TextArea

Initial Tags
javascript

Initial Language
JavaScript