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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.