JSFiddle - React, Tailwind, and code Playground
by momenelkamri
HTML
<div class="modal">
<h1>
inside modal
</h1>
<a href="#" class="hide">test hide</a>
<a href="#">test</a>
<button>test 2</button>
<input type="button" value="go outside" id="goOutSide" />
</div>
<a href="#" class="outside">outside modal</a>
<a href="#" class="">outside modal</a>
<a href="#" class="">outside modal</a>
<a href="#" class="">outside modal</a>
CSS
.hide {
display: none;
}
JavaScript
var tabbableElements = 'a[href], input[type=button], button';
var keepFocus = function (context) {
var allTabbableElements = context.querySelectorAll(tabbableElements);
allTabbableElements = Array.prototype.filter.call(allTabbableElements, function(element) {
if (element.offsetWidth > 0 && element.offsetHeight > 0) {
return element;
}
});
console.log('allTabbableElements ', allTabbableElements);
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) {
console.log('event.target ', event.target);
// 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();
// outside
var goOutSide = function() {
console.log(document.querySelector('.outside'));
document.querySelector('.outside').focus();
}
document.getElementById("goOutSide").addEventListener ("click", goOutSide, false);