We can get Cursor Position with selection concept.  If browser is IE then create empty selection range from current position to starting position, then get selection length which will be present cursor position. If browser is not IE then get selection start which will be present cursor position.

Markup

<input value="sample input value" ng-click="getCursorPos($event)" ng-keyup="getCursorPos($event)"/>
<div> Cursor Position : <b ng-bind="cursorPosVal"></b></div>

Script

$scope.getCursorPos = function($event) {
   var myEl = $event.target;
   $scope.doGetCaretPosition(myEl);  
};
    
$scope.doGetCaretPosition = function(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
    $scope.cursorPosVal = iCaretPos;
};

1 comment:

  1. How can i insert text at textarea on last focused cursor position(caret) using Angularjs2

    ReplyDelete

Blogroll

Popular Posts