Focus Traps - Modal Cookie Banner Example

by tohuwabohu_io

HTML

<body>
    <dialog id="modal-window" class="popup-overlay modal" aria-modal="true">
        <div class="popup">
            <div>
                <h2>Cookies 🍪</h2>
                <p>
                    Very important information in regard to whom you will sell your soul to.
                </p>
                <p>
                    Allow or Prohibit:
                </p>
                <div class="popup-controls popup-controls-checkboxes">
                    <input id="technical" type="checkbox" checked>
                    <label for="technical">Technical Cookies</label>
                    <input id="analytical" type="checkbox" checked>
                    <label for="analytical">Analytical Cookies</label>
                    <input id="thirdParty" type="checkbox" checked>
                    <label for="thirdParty">3rd Party Cookies</label>
                </div>
            </div>
            <div class="popup-button-container">
                <button class="accept" onclick="hideOverlay(true)">
                    Accept
                </button>
                <button onclick="hideOverlay(true)">
                    Decline
                </button>
            </div>
        </div>
    </dialog>
    <main>
        <section>
            <h1>Very cool website that needs cookies</h1>
            <p>
                Our quality content mainly consists of cats in various poses.
            </p>
            <a href="#">Here is a link that would get focused if the focus trap would not exist.</a>
            <p>
                Also dogs that sniff each other's butts are seen here.
            </p>
            <a href="#">Here is another link that would get focused if the focus trap would not exist.</a>
            <p>
                Have you ever watched a cockatoo solving a Rubik's cube? We neither.
            </p>
            <a href="#">Here is yet another link that would get focused if the focus trap would not exist.</a>
        </section>

       ...

CSS

.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: visible;
  background-color: rgba(255, 255, 255, 0.70);
  display: none;
}

.modal {
  display: flex;
  align-items: center;
}

.popup {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;
  border-radius: 10px;
  border: 1px solid black;
  padding: 1em;
  margin: auto;
  gap: 1em;
  max-width: 500px;
  background-color: #fff;
}

.popup-controls {
  display: grid;
  grid-template-columns: 2em auto;
  gap: 1em;
}

.popup-button-container {
  display: flex;
  flex-direction: row;
  gap: 1em;
}

.form-grid {
  display: grid;
  grid-template-columns: auto auto;
  max-width: 600px;
  gap: 1em;
}

.form-submit {
  margin: 1em;
}

button {
  border-radius: 5px;
  border: 1px solid black;
  padding: 0.25em;
  font-size: 1em;
  background: white;
}

.accept {
  background: #3584e4;
}

JavaScript

document.addEventListener('DOMContentLoaded', () => {
  const focusableElements = Array.from(document
    .querySelectorAll('div[class~=popup-controls] > input, div[class=popup-button-container] > button'));

  const first = focusableElements[0];
  const last = focusableElements[focusableElements.length - 1];

  document.addEventListener('keydown', (e) => {
    const overlay = document.querySelector('dialog.popup-overlay.modal');

    if (overlay && e.key === 'Tab') {
      if (!focusableElements.includes(e.target)) {
        trap(e, first);
      } else if (e.target === last && !e.shiftKey) {
        trap(e, first);
      } else if (e.target === first && e.shiftKey) {
        trap(e, last);
      }
    }
  });
});

const trap = (e, element) => {
  e.preventDefault();
  element.focus();
}

const hideOverlay = (hide) => {
  const overlay = document.querySelector('dialog[id=modal-window]');

  if (hide === true) {
    overlay.setAttribute('aria-hidden', 'true');

    overlay.classList.remove('modal');
  } else {
    overlay.setAttribute('aria-hidden', 'false');

    overlay.classList.add('modal');
  }
}