I am working on a site in which supports keyboard navigation and other various accessibility features. For those not in the know, some users prefer to navigate the web by using their keyboard (Tab to go forwards, Tab + Shift to go backwards, Enter to select, etc) instead of their mice and cursors to click and scroll around. One of the major keyboard navigation issues lies on pop-ups, modules or overlays.
Overlays are often ignored through keyboard navigation, with no way of interacting with them.
This video on YouTube explains what happens very well (skip to ~5:44 to get an idea).
There is a way to fix this issue, which is done by making a "focus trap". A focus trap basically forces the user's selector to focus on certain elements and loop around them without being able to interact with other outer elements.
In my case, I have created a JavaScript file which, if linked on a page, pops up a dialog as a content warning. It works perfectly, until I start browsing the page with my keyboard. The dialog is completely ignored and I can engage with the page even though I am not supposed to. So I thought to have a script that transfers the selection's focus on the elements inside the dialog and loop between them if possible, so that the user is required to choose whether they want to engaging with the page or not. In short, enable a focus trap.
I have tried implementing & modifying a variety of code snippets, but none of them seemed to work since I don't know what I'm doing.
I am still new to learning JavaScript!
Here is my code simplified for reference:
JS:
let warninghtml = `
<dialog open id="warningBoxbg"> //note that the dialog is automatically open, so activating the trap on transition might not work
<div class="warningBox">
<div id="warningContent"></div>
//these are the elements I want to trap the focus on:
<a role="button" class="close">Proceed</a> / <a role="button" onclick="history.back()">Go back</a>
</div>
</dialog>
`
document.write(warninghtml);
//misc practical code; no need to focus here much I guess
if (document.getElementById("warningBoxbg")) {
let modal = document.getElementById("warningBoxbg");
let span = document.getElementsByClassName("close")[0];
span.onclick = function() {
modal.style.display = "none";
}
}
if (document.getElementById("warningContent")) {
document.getElementById("warningContent").innerHTML = "<img src='some_cool_img_here.png'><h4>Yo, this page is weird!!!</h4>";
}
CSS:
/* dialog styling */
#warningBoxbg {
display: block;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.8);
backdrop-filter: blur(10px);
z-index: 999;
}
/* misc styling, not that important */
.warningBox { margin: 15% auto; width: 40%; max-width: 700px; }
#warningContent img { float: right; }
.warnoptions { margin-top: -250px; margin-right: auto; margin-left: auto; padding: 20px; border: 1px solid #888; width: 10%; }
So, how can I achieve this?
If something has not been made clear, let me know.