Fully Accessible Modal Window With Pure JavaScript

Category: Javascript , Modal & Popup | February 18, 2016
Author:edenspiekermann
Views Total:1,471 views
Official Page:Go to website
Last Update:February 18, 2016
License:MIT

Preview:

Fully Accessible Modal Window With Pure JavaScript

Description:

This is a pure JavaScript version of Greg Kraus’s accessible-modal-dialog that allows to implement a fully accessible modal window for screen reader users. No any dependencies required.

How to use it:

Put the accessible-modal-dialog.js script into your webpage.

<script src="accessible-modal-dialog.js"></script>

Create the modal content.

<div class="modal" aria-hidden="true" id="my-accessible-modal">
  <div class="modal-overlay" tabindex="-1" data-modal-hide></div>
  <div class="modal-content" aria-labelledby="modalTitle" aria-describedby="modalDescription" role="dialog">
    <div role="document">
      <h1 id="modalTitle">Modal Title</h1>

      Modal Content Goes here

      <button data-modal-hide class="modal-close" title="Close registration form">&times;</button>
    </div>
  </div>
</div>

Necessary styling for the modal to work.

.modal-overlay {
  z-index: 2;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.66);
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}

.modal-content {
  background-color: rgb(255, 255, 255);
  z-index: 3;
  position: fixed;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

.modal[aria-hidden="true"] {
  display: none;
}

Create a modal toggle button.

<button data-modal-show="my-accessible-modal">view the modal window</button>

Initialize the modal window.

(function () {
  document.addEventListener('DOMContentLoaded', function () {
    var modalEl = document.getElementById('my-accessible-modal');
    var mainEl = document.getElementById('main');
    var modal = new window.Modal(modalEl, mainEl);
  });
}());

To manually control the modal:

modal.show()
modal.hide()

You Might Be Interested In:


Leave a Reply