Skip to content

Instantly share code, notes, and snippets.

@jonathanconway
Created June 26, 2015 06:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathanconway/899a0856a8b16245cca3 to your computer and use it in GitHub Desktop.
Save jonathanconway/899a0856a8b16245cca3 to your computer and use it in GitHub Desktop.
jQuery plugin that makes individual radio-buttons focusable using the keyboard only. (Useful for accessibility, on a case-by-case basis.)
$.fn.radioTabbable = function () {
var groups = [];
// group the inputs by name
$(this).each(function () {
var el = this;
var thisGroup = groups[el.name] = (groups[el.name] || []);
thisGroup.push(el);
});
$(this).on('keydown', function (e) {
setTimeout(function () {
var el = e.target;
var thisGroup = groups[el.name] = (groups[el.name] || []);
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