Skip to content

Instantly share code, notes, and snippets.

@pookie13
Last active August 23, 2016 06:22
Show Gist options
  • Save pookie13/5e2aa340ee7a7b6be103bc55f8877fc1 to your computer and use it in GitHub Desktop.
Save pookie13/5e2aa340ee7a7b6be103bc55f8877fc1 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html ng-app="" ng-controller="myCtrl">
<body>
<input value="sample input value" ng-click="getCursorPos($event)" ng-keyup="getCursorPos($event)" id="searchTxt" type="text" />
<button ng-click="showAlert()">
<div> Cursor Position : <b ng-bind="pos"></b></div>
<script>
function myCtrl($scope) {
$scope.pos = document.getElementById('searchTxt').value.length ;
$scope.cursorPosVal = -1;
$scope.showAlert = function() {
var text = document.getElementById('searchTxt').value;
document.getElementById('searchTxt').value=text.substring(0,$scope.pos-1)+text.substring($scope.pos,text.length);
$scope.pos= $scope.pos-1;
};
$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.pos=iCaretPos;
$scope.cursorPosVal = iCaretPos;
};
}
</script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment