Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I position my cursor in an input field based on a keypress?

Tags:

angularjs

I am capturing keypresses like this:

<div class="contentView"
     ng-keypress="phs.keyEnter($event)">

keyEnter = ($event): void => {
    var a = $event;

How can I make it so that clicking a key will make the cursor go to an input field:

 <input ng-change="phs.englishChange();"
               ng-model="phs.english"
               ng-model-options="{ debounce: 750 }"
               style="width:6rem;"
               type="text" />
like image 890
Alan2 Avatar asked Jan 28 '18 06:01

Alan2


1 Answers

I think directive can help us to have a more universal and re-usable solution to your problem, because it is the most good place to attach a specified behavior to that input element. So here is a custom doOnKeypress directive that accepts a key (doOnKeypress) and an optional callback (acceptOn) to check the target of the fired keypress event and a callback (onKeypress) that is going to be fired if all conditions are satisfied.

In the example below the input will be focused whenever a keyboard button is pressed. I left the comments so you can modify it for your needs (hope the general idea is clear):

angular.module("app", [])
    .controller("TestController", ["$scope", function ($scope) {
        $scope.acceptOn = function (target, element) {
            console.log(target);     // you can make any checks for target by passing this into a directive
            return element[0] !== target[0]; //target is not the same input element
        };
        $scope.focusOn = function (element) {
            element[0].focus(); // or whatever you want with element
        };
    }]).directive('doOnKeypress', ['$document', function ($document) {
    return {
        restrict: 'A',
        scope: {
            doOnKeypress: '@',
            acceptOn: '&?',
            onKeypress: '&'
        },
        link: function postLink(scope, element) {

            function keypress(e) {
                var target = angular.element(e.target);
                var targetIsAcceptable = angular.isFunction(scope.acceptOn) ? scope.acceptOn({
                    target: target,
                    element: element
                }) : true; // add the condition to test the target
                var specialKeyPressed = e.shiftKey || e.ctrlKey || e.altKey || e.metaKey; // in case you need to check any special keys

                if (targetIsAcceptable && !specialKeyPressed) {
                    var keyCode = e.which || e.keyCode;
                    var key = String.fromCharCode(keyCode);
                    if ("*" === scope.doOnKeypress || key.toLowerCase() === scope.doOnKeypress.toLowerCase()) {  // any check before focusing  (lets say * - is any key)
                        e.preventDefault(); // prevent from typing into the input
                        scope.onKeypress({element: element});
                    }
                }
            }

            $document.on('keypress', keypress);

            scope.$on('$destroy', function () {
                $document.off('keypress', keypress);
            });
        }
    };
}]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>

<body ng-app="app" class="">
  <div ng-controller="TestController" class='listen-to-keypress'>
   TestController

   <br/>
    
   <div>
   
    <input ng-change="phs.englishChange();"
               ng-model="phs.english"
               ng-model-options="{ debounce: 750 }"
               style="width:6rem;"
               do-on-keypress='A'
               accept-on='acceptOn(target, element)'
               on-keypress='focusOn(element)'
               type="text" />
   
   </div>

  </div>
</body>

UPDATE: added element argument to the acceptOn callback to allow to compare target with the same element, since we want to let the user typing into this input element in our case.

like image 136
Stanislav Kvitash Avatar answered Oct 04 '22 21:10

Stanislav Kvitash