Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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
You can’t perform that action at this time.