Created
January 25, 2019 01:08
-
-
Save ryanscherler/125f66b8d321bb629f2fa1b23b0484b0 to your computer and use it in GitHub Desktop.
Simple Class Modal
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
/* | |
Usage: | |
<a href="#url" data-modal-open="modal-123">Open Modal</a> | |
<div class="modal" data-modal="modal-123"> | |
<button data-modal-close="modal-123">Close Modal</button> | |
... | |
</div> | |
*/ | |
export default class { | |
constructor() { | |
this.opener = 'data-modal-open' | |
this.closer = 'data-modal-close' | |
this.target = 'data-modal' | |
this.modal = { | |
className: { | |
base: 'modal', | |
visible: 'modal--visible', | |
}, | |
} | |
this.bindEvents() | |
} | |
bindEvents() { | |
const self = this | |
const openers = document.querySelectorAll(`[${self.opener}]`) | |
const closers = document.querySelectorAll(`[${self.closer}]`) | |
if (openers) { | |
openers.forEach(opener => { | |
opener.addEventListener('click', function(event) { | |
event.preventDefault() | |
self.openModal(this.getAttribute(self.opener)) | |
}) | |
}) | |
} | |
if (closers) { | |
closers.forEach(closer => { | |
closer.addEventListener('click', function(event) { | |
event.preventDefault() | |
self.closeModal(this.getAttribute(self.closer)) | |
}) | |
}) | |
} | |
document.onkeydown = event => { | |
if (event.keyCode === 27) { | |
const modals = document.querySelectorAll(`[${self.target}]`) | |
if (modals) { | |
modals.forEach(modal => { | |
modal.classList.remove(self.modal.className.visible) | |
}) | |
} | |
} | |
} | |
} | |
openModal(target) { | |
const modal = document.querySelector(`[${this.target}=${target}]`) | |
if (modal) { | |
modal.classList.add(this.modal.className.visible) | |
} | |
} | |
closeModal(target) { | |
const modal = document.querySelector(`[${this.target}=${target}]`) | |
if (modal) { | |
modal.classList.remove(this.modal.className.visible) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment