Created
September 29, 2021 20:47
-
-
Save ten1seven/385ed523b01eba06c29768a34b2a8e1d to your computer and use it in GitHub Desktop.
Modal JavaScript from Urban Land Institute
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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