Skip to content

Instantly share code, notes, and snippets.

@edrdesigner
Forked from jonathanconway/radioTabbable.ng.js
Created April 5, 2019 14:03
Show Gist options
  • Save edrdesigner/01d230da412c0ebb771612032c7f6e1f to your computer and use it in GitHub Desktop.
Save edrdesigner/01d230da412c0ebb771612032c7f6e1f to your computer and use it in GitHub Desktop.
Angular Directive that makes individual radio-buttons focusable using the keyboard only. (Useful for accessibility, on a case-by-case basis.)
/**
* @ngdoc directive
* @name radioTabbable
* @requires none
* @description
* Makes individual radio buttons focuseable using the TAB key.
* (By default, pressing TAB while on a radio button would have shifted focus to the next control outside of the radio group.)
* @usage
* <input type="radio" name="radioGroup" value="0" radio-tabbable="" />
* <input type="radio" name="radioGroup" value="1" radio-tabbable="" />
*/
angular.module('app', []).directive('radioTabbable', [function() {
var groups = {};
return {
restrict: 'A',
link: {
pre: function(scope, element, attrs) {
var el = element[0];
var thisGroup = groups[el.name] = (groups[el.name] || []);
thisGroup.push(el);
el.addEventListener('keydown', function (e) {
setTimeout(function () {
var indexOfTarget = thisGroup.indexOf(e.target);
if (e.keyCode === 9) {
if (indexOfTarget < (thisGroup.length - 1) && !(e.shiftKey)) {
thisGroup[indexOfTarget + 1].focus();
}
else if (indexOfTarget > 0 && e.shiftKey) {
thisGroup[indexOfTarget - 1].focus();
}
}
});
});
}
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment