Apple Pie
Apple Pie

Reputation: 93

Handling focus on a toggle button

I am trying to keep the focus on the toggle button after it gets pressed. Right now, when I click on the button, the focus jumps to the top of the page. I am not sure what I am doing wrong.

Here is the code:

HTML

  <button ng-if=“test” ng-click=“deactivate()">Deactivate</button>
  <button  ng-if=“!test” ng-click="activate()”>Activate </button>

JS

 $scope.activate = function () {
          var activateButton = document.activeElement;
            if ($scope.some.length) {
                $scope.enableSome($scope.some, true);
            }
            activateButton.onclick = function () {
              activateButton.focus();
            };
        };

 $scope.deactivate = function () {
          var activateButton = document.activeElement;
            if ($scope.some.length) {
                $scope.enableSome($scope.some, false);
            }
          activateButton.onclick = function () {
            activateButton.focus();
          };
        };

Upvotes: 0

Views: 533

Answers (1)

alexhughesking
alexhughesking

Reputation: 2007

You actually have two buttons that are added/removed from the DOM based on the ng-if condition (documentation).

Your button is not getting focused because the activate button is getting removed while the deactivate button is added, and vice versa.

We can refactor the two buttons into one using a toggleActivation() method.

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.test = false;
  $scope.some = [1, 2, 3];

  $scope.enableSome = function(some, activate) {
    //Do whatever
    console.log('enableSome called with activate = ' + activate);
  }

  $scope.toggleActivation = function() {

    //Toggle the state
    $scope.test = !$scope.test;
    
    if ($scope.some.length) {
      $scope.enableSome($scope.some, $scope.test);
    }
    
    //The button is still focused!
    console.log('Focused element: ', document.activeElement);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
  <button ng-click="toggleActivation()">
    {{test ? "Deactivate" : "Activate"}}
  </button>
</div>

Upvotes: 1

Related Questions