Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Trap focus inside modal. Fixes #268 #294

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions jquery.modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,9 @@
open: function() {
var m = this;
this.block();
// Store previous focus
this.previousFocus = document.activeElement;

this.anchor.blur();
if(this.options.doFade) {
setTimeout(function() {
Expand Down Expand Up @@ -148,6 +151,7 @@
} else {
this.$elm.css('display', 'inline-block');
}
this.trapFocus();
this.$elm.trigger($.modal.OPEN, [this._ctx()]);
},

Expand All @@ -164,6 +168,7 @@
_this.$elm.trigger($.modal.AFTER_CLOSE, [_this._ctx()]);
});
}
this.releaseFocus();
this.$elm.trigger($.modal.CLOSE, [this._ctx()]);
},

Expand All @@ -179,6 +184,46 @@
if (this.spinner) this.spinner.remove();
},

// Trap focus in modal for screen readers & keyboard navigation
trapFocus: function() {
// All focusable elements
var focusableElements = 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';

var firstFocusableElement = this.$elm[0].querySelectorAll(focusableElements)[0]; // get first element to be focused inside modal
var focusableContent = this.$elm[0].querySelectorAll(focusableElements);
var lastFocusableElement = focusableContent[focusableContent.length - 1]; // get last element to be focused inside modal


$(this.$elm).on('keydown', function(e) {
let isTabPressed = e.key === 'Tab' || e.keyCode === 9;

if (!isTabPressed) {
return;
}

if (e.shiftKey) { // if shift key pressed for shift + tab combination
if (document.activeElement === firstFocusableElement) {
lastFocusableElement.focus(); // add focus for the last focusable element
e.preventDefault();
}
} else { // if tab key is pressed
if (document.activeElement === lastFocusableElement) { // if focused has reached to last focusable element then focus first focusable element after pressing tab
firstFocusableElement.focus(); // add focus for the first focusable element
e.preventDefault();
}
}
});

firstFocusableElement.focus();
},

releaseFocus: function() {
$(this.$elm).off('keydown');

// Restore previous focus
this.previousFocus.focus();
},

//Return context for custom events
_ctx: function() {
return { elm: this.$elm, $elm: this.$elm, $blocker: this.$blocker, options: this.options, $anchor: this.anchor };
Expand Down