I am trying to implement a mechanism where specific items on a screen are navigable using arrows keys.
At the moment, I am drawing a red box around items as they move and pressing enter activates them.
I have the following directive: (credits here and here)
.directive("moveNext", function() {
return {
restrict: "A",
link: function($scope, element,attrs) {
element.bind("keyup", function(e) {
if (e.which == 37) {
console.log ("MOVE LEFT:" + JSON.stringify(element));
element[0].classList.remove('selected');
var partsId = attrs.id.match(/move-(\d+)/);
console.log ("CURRENT PARTS="+JSON.stringify(partsId));
var currentId = parseInt(partsId[1]);
console.log ("Looking for move-"+(currentId-1));
var nextElement = angular.element(document.querySelectorAll('#move-' + (currentId - 1)));
// var $nextElement = element.next().find('movehere');
if(nextElement.length) {
nextElement[0].classList.add('selected');
nextElement[0].focus();
// $nextElement[0].style.border='5px solid red';;
}
}
if (e.which == 39) {
console.log ("MOVE RIGHT:" + JSON.stringify(element));
element[0].classList.remove('selected');
var partsId = attrs.id.match(/move-(\d+)/);
var currentId = parseInt(partsId[1]);
console.log ("CURRENT PARTS="+JSON.stringify(partsId));
var currentId = parseInt(partsId[1]);
var nextElement = angular.element(document.querySelectorAll('#move-' + (currentId + 1)));
console.log ("Looking for move-"+(currentId+1));
// var $nextElement = element.next().find('movehere');
if(nextElement.length) {
nextElement[0].classList.add('selected');
nextElement[0].focus();
// $nextElement[0].style.border='5px solid red';;
}
}
if (e.which == 13) {
console.log ("ENTER:" + JSON.stringify(element));
// element.triggerHandler('click');
}
});
if (event) event.preventDefault();
}
}
})
And then in the template I have the following, for example:
<div>
<button move-next id="move-1" ng-click="d1()">Yes</button>
<button move-next id="move-3" ng-click="d1()">Yes</button>
<button ng-click="d1()">No</button>
<button move-next id="move-2" ng-click="d1()">Yes</button>
</div>
<a href="d2()" move-next id="move-4">Yes</a> <!-- PROBLEM -->
<a href="d2()" move-next id="move-5">Yes</a> <!-- NEVER COMES HERE -->
The nice part is I can now navigate to any "clickable" element depending on the ID order I set, which is my intention. The problem is that focus()
only works on items that are focusable, so once "move-4" is highlighted by the directive, the focus()
doesn't really work so I can never move "next" to "move-5"
thanks