Skip to content

Instantly share code, notes, and snippets.

@gu-stav
Forked from drublic/keep-focus.js
Created July 2, 2013 07:02
Show Gist options
  • Save gu-stav/5907263 to your computer and use it in GitHub Desktop.
Save gu-stav/5907263 to your computer and use it in GitHub Desktop.
Keep the focus inside a lightbox/ element. Elegant solution.
var tabbableElements = 'a[href], area[href], input:not([disabled]),' +
'select:not([disabled]), textarea:not([disabled]),' +
'button:not([disabled]), iframe, object, embed, *[tabindex],' +
'*[contenteditable]';
var keepFocus = function (context) {
var allTabbableElements = context.querySelectorAll(tabbableElements);
var firstTabbableElement = allTabbableElements[0];
var lastTabbableElement = allTabbableElements[allTabbableElements.length - 1];
var keyListener = function (event) {
var keyCode = event.which || event.keyCode; // Get the current keycode
// Polyfill to prevent the default behavior of events
event.preventDefault = event.preventDefault || function () {
event.returnValue = false;
};
// If it is TAB
if (keyCode === 9) {
// Move focus to first element that can be tabbed if Shift isn't used
if (event.target === lastTabbableElement && !event.shiftKey) {
event.preventDefault();
firstTabbableElement.focus();
// Move focus to last element that can be tabbed if Shift is used
} else if (event.target === firstTabbableElement && event.shiftKey) {
event.preventDefault();
lastTabbableElement.focus();
}
}
};
context.addEventListener('keydown', keyListener, false);
};
// Call the function when the part of the page gets focus
var modal = document.querySelector('.modal');
keepFocus(modal);
modal.focus();
@rependa
Copy link

rependa commented Sep 21, 2017

This is great. How would you remove it, once applied? Eg, using in a fullscreen view of a piece of content within a page. When the fullscreen view is removed, I'd like to unbind it from the 'context'

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