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

LVL 1
photondesignAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
leakim971Connect With a Mentor PluritechnicianCommented:
0
 
photondesignAuthor Commented:
Looks promising.  I will give it a go tonight and see how it goes.  Thanks.
0
 
leakim971PluritechnicianCommented:
You're welcome!
0
 
photondesignAuthor Commented:
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.
0
 
leakim971PluritechnicianCommented:
Thanks for the points!
0
All Courses

From novice to tech pro — start learning today.