Skip to content

Instantly share code, notes, and snippets.

@dsternlicht
Last active November 27, 2018 15:01
Show Gist options
  • Save dsternlicht/776d632c9e7ba1a6b12fa58f054ca5fc to your computer and use it in GitHub Desktop.
Save dsternlicht/776d632c9e7ba1a6b12fa58f054ca5fc to your computer and use it in GitHub Desktop.
Main script of our vanilla JS popup
var btn = document.getElementById('modal_opener');
var modal = document.querySelector('.modal');
function attachModalListeners(modalElm) {
modalElm.querySelector('.close_modal').addEventListener('click', toggleModal);
modalElm.querySelector('.overlay').addEventListener('click', toggleModal);
}
function detachModalListeners(modalElm) {
modalElm.querySelector('.close_modal').removeEventListener('click', toggleModal);
modalElm.querySelector('.overlay').removeEventListener('click', toggleModal);
}
function toggleModal() {
var currentState = modal.style.display;
// If modal is visible, hide it. Else, display it.
if (currentState === 'none') {
modal.style.display = 'block';
attachModalListeners(modal);
} else {
modal.style.display = 'none';
detachModalListeners(modal);
}
}
btn.addEventListener('click', toggleModal);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment