-
-
Save Frique/5977792 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
jQuery version of the original. Also makes it work in IE7/8 (not tested in 6 :))