officegunner
officegunner

Reputation: 97

Caret index position cross browser?

I'm making a WYSIWYG editor, and I need to know how to get caret position working. It appears that there's no obvious way of doing it cross-platform.

I just need the syntax. Please don't point me towards the Mozilla developer page; I didn't find it particularly useful. I'm using a content editable div.

source that i looked at

Upvotes: 2

Views: 4223

Answers (1)

Jaspreet Chahal
Jaspreet Chahal

Reputation: 2750

try this

function doGetCaretPosition (oField) {

 // Initialize
 var iCaretPos = 0;

 // IE Support
 if (document.selection) { 

   // Set focus on the element
   oField.focus ();

   // To get cursor position, get empty selection range
   var oSel = document.selection.createRange ();

   // Move selection start to 0 position
   oSel.moveStart ('character', -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);
}

Upvotes: 9

Related Questions