Link to home
Start Free TrialLog in
Avatar of photondesign
photondesignFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Caret Position in Textarea using IE8 and Javascript

I need to find the current caret (cursor) position in a textarea in Internet Explorer 8.  The attached code works in firefox, but not in IE8.  It has provision for IE but I think it only works in IE7, there is a problem with the createRange in IE8 when nothing is actually selected.

I need the position of the caret, relative to the start of the text in the textarea, the content may include new lines, etc.
// Function used to get caret's position
getCaretPosition = function(oField)
{
	// Initialize
	var iCaretPos = 0;

	// IE Support
	if (document.selection)
	{
		oField.focus ();
		
		// To get cursor position, get empty selection range
		var oSel = document.selection.createRange();

		// Move selection start to 0th position
		oSel.moveStart("character", 0 - oField.value.length);

		// The caret position is selection length
		iCaretPos = oSel.text.length;
	}
	// Firefox support
	else if (oField.selectionStart || oField.selectionStart == "0")
	{
		iCaretPos = oField.selectionStart;
	}

	// Return results
	return (iCaretPos);
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of photondesign

ASKER

Looks promising.  I will give it a go tonight and see how it goes.  Thanks.
You're welcome!
I used bits of that code rather than using the actual module. As it was an modification to the jquery autocorrect module that I was creating.  Now all works great. Thanks.
Thanks for the points!