Skip to content

Instantly share code, notes, and snippets.

@realalexhomer
Last active November 20, 2015 20:42
Show Gist options
  • Save realalexhomer/cd3d816fd6e5b1d28211 to your computer and use it in GitHub Desktop.
Save realalexhomer/cd3d816fd6e5b1d28211 to your computer and use it in GitHub Desktop.
// assign elements that you want to be tabbable a data-tabbable ="true" property.
// If elements are hidden, they won't be considered.
keepFocus = function($el){
var tabbableEls = $el.parent().find($('[data-tabbable="true"]'));
$.each(tabbableEls, function(idx, el){
$(el).attr({'tabindex': 0});
});
findFirst().focus();
$el.parent().on('keydown', keyListener);
function keyListener(ev){
var keyCode = ev.keyCode,
$currEl = $(ev.target),
$first, $last;
if (keyCode === 9 && !event.shiftKey){
$last = findLast();
if ($currEl[0] === $last[0]){
$first = findFirst();
event.preventDefault();
$first.focus();
return;
}
} else if (keyCode === 9 && event.shiftKey){
$first = findFirst();
if ($currEl[0] === $first[0]) {
$last = findLast();
event.preventDefault();
$last.focus();
return;
}
}
}
function isVisible(idx, el){
if ($(el).is(":visible")) {
return true;
} else {
return false;
}
}
function findFirst(){
return tabbableEls.filter(isVisible).first();
}
function findLast(){
return tabbableEls.filter(isVisible).last();
}
};
module.exports = keepFocus;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment