Changing Tab Focus Behavior Using Angular
The example below uses 2 Angular directives to change the focus behavior when pressing the tab key.The first directive is used to assign a name to a 'focusable' element.
module.exports = function (_module) { _module.directive('focusName', function () { return { restrict: 'A', link: function ($scope, element, attributes) { $scope.focusRegistry = $scope.focusRegistry || {}; $scope.focusRegistry[attributes.focusName] = element[0]; } }; }); };Line 6 lazily creates a scope object called focusRegistry. This object will be used to store all 'focusable' elements within the scope.
Line 7 registers the element using the value of the attribute focusName (focus-name) as the key.
The second directive is used declare the which element will be focused when the tab key is pressed. It will also be responsible for handling the events triggered by pressing the tab key.
module.exports = function (_module) { _module.directive('nextFocus', function () { return { restrict: 'A', link: function ($scope, element, attributes) { element.bind('keydown keypress', function (event) { if (event.which === 9) { // Tab var focusElement = $scope.focusRegistry[attributes.nextFocus]; if (focusElement) { if (!focusElement.hidden && !focusElement.disabled) { focusElement.focus(); event.preventDefault(); return; } } console.log('Unable to focus on target: ' + attributes.nextFocus); } }); } }; }); };Line 7 captures the keydown or keypress event on the tab key (9).
Line 8 retrieves the focus element from the registry using the value of the attribute nextFocus (next-focus).
Lines 10 to 14, moves the focus to the element if it is possible.
If the focus cannot be moved to the specified element, the default behavior of tab will take effect.
Below is an example on how to use both directives:
<input name="1" focus-name="1" next-focus="2" value="next focus goes to 2" /> <input name="2" focus-name="2" next-focus="3" value="next focus goes to 3" /> <input name="3" focus-name="3" next-focus="1" value="next focus goes back to 1" /> <input name="4" value="will not be focused" />A working example is available at Plunker.
It is important to note that this approach will only work on elements within the same scope.
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment