Friday, May 15, 2009

Get cursor position within Textarea

Thanks to someone sharing the javascript code for getting curssor position within web component like Textarea on both IE and Firefox browser. The code would look like this:

function doGetCaretPosition(ctrl) {
var CaretPos = 0;
// IE Support
if (document.selection) {
// The current selection
var range = document.selection.createRange();
// We'll use this as a 'dummy'
var stored_range = range.duplicate();
// Select all text
stored_range.moveToElementText( ctrl );
// Now move 'dummy' end point to end point of original range
stored_range.setEndPoint( 'EndToEnd', range );
// Now we can calculate start and end points
CaretPos = stored_range.text.length - range.text.length;
}
// Firefox support
else if (ctrl.selectionStart ctrl.selectionStart == "0")
CaretPos = ctrl.selectionStart;
return (CaretPos);
}


It does it's job very well, except when you press the navigation keys like arrow keys or even [Shift] key inside Textarea. In IE (only in IE), the cursor position will always shift to the end of the string after you press keys like those metioned above. To make it better, we can avoid any action taken when those problematic keycodes are detected.

var intKey = 0;
if (!is_gecko){
var evnt = window.event;
intKey = parseInt(evnt.keyCode);
}
// Process only if key code is not in ignore list (Fix IE bug)

//Firefox will pass this condition
if (intKey!=8 && intKey!=16
&& intKey!=17 && intKey!=18
&& intKey!=33 && intKey!=34
&& intKey!=37 && intKey!=38
&& intKey!=39 && intKey!=40) {

var posStart = doGetCaretPosition(elm);
...processing string and move caret if you like

}

Firefox is always fine with this, it won't reset the cursor positon when you call selectionStart property. Therefore, we only need to be aware of IE's wired behaviour;-)

No comments:

Post a Comment