Skip to content

Instantly share code, notes, and snippets.

@Frique
Forked from drublic/keep-focus.js
Last active December 19, 2015 15:38
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Frique/5977792 to your computer and use it in GitHub Desktop.
var tabbableElements = 'a[href], area[href], input:not([disabled]),' +
'select:not([disabled]), textarea:not([disabled]),' +
'button:not([disabled]), iframe, object, embed, *[tabindex],' +
'*[contenteditable]';
function keepFocus($context){
var $allTabbableElements = $context.find(tabbableElements);
var $firstTabbableElement = $allTabbableElements.first();
var $lastTabbableElement = $allTabbableElements.last();
$context.on('keydown', function(event){
// If it is TAB
if(event.keyCode === 9){
var $target = $(event.target);
// Move focus to first element that can be tabbed if Shift isn't used
if($target.is($lastTabbableElement) && !event.shiftKey){
event.preventDefault();
$firstTabbableElement.focus();
// Move focus to last element that can be tabbed if Shift is used
}else if($target.is($firstTabbableElement) && event.shiftKey){
event.preventDefault();
$lastTabbableElement.focus();
}
}
});
}
// Call the function when the part of the page gets focus
var $modal = $('.modal').focus();
keepFocus($modal);
@Frique
Copy link
Author

Frique commented Jul 11, 2013

jQuery version of the original. Also makes it work in IE7/8 (not tested in 6 :))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment