Skip to content

Instantly share code, notes, and snippets.

@ten1seven
Created September 29, 2021 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ten1seven/385ed523b01eba06c29768a34b2a8e1d to your computer and use it in GitHub Desktop.
Save ten1seven/385ed523b01eba06c29768a34b2a8e1d to your computer and use it in GitHub Desktop.
Modal JavaScript from Urban Land Institute
import MicroModal from 'micromodal';
export default class Modal {
containerId = 'site-container'
dismissable = true
constructor(el) {
this.variables(el)
this.setup()
this.events()
}
variables(el) {
this.button = el
this.modalId = this.button.getAttribute('aria-controls')
this.containerId = this.button.dataset.siteContainer || this.containerId
this.modalEl = document.getElementById(this.modalId)
this.documentEl = document.documentElement
this.siteContainer = document.getElementById(this.containerId)
if (this.modalEl.hasAttribute('data-modal-not-dismissable')) {
this.dismissable = false
}
}
setup() {
this.modal = MicroModal
if (this.modalEl.classList.contains('is-open')) {
this.open()
}
}
events() {
this.button.addEventListener('click', this.open)
}
open = () => {
this.modal.show(this.modalId, {
onClose: this.onClose
})
this.onOpen()
this.documentEl.classList.add('-freeze')
if (this.siteContainer) {
this.siteContainer.setAttribute('aria-hidden', 'true')
}
}
onOpen = () => {
// fix improper usage of aria-hidden="false" by micromodal
this.modalEl.removeAttribute('aria-hidden')
}
onClose = () => {
this.documentEl.classList.remove('-freeze')
if (this.siteContainer) {
this.siteContainer.removeAttribute('aria-hidden')
}
if (!this.dismissable) {
// If you can't dismiss this modal, then re-open it
// Fixes an edge case where you can still use ESC to close a
// content gate modal
setTimeout(() => {
this.open()
}, 50)
}
}
}
/*
Usage:
======
<button
aria-controls="modal-id"
data-module="modal"
data-site-container="site-container"
>
Open
</button>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment