Skip to content

Instantly share code, notes, and snippets.

@giventofly
Last active November 30, 2020 21:39
Show Gist options
  • Save giventofly/48163804a4b15bb75f9d133269e8e886 to your computer and use it in GitHub Desktop.
Save giventofly/48163804a4b15bb75f9d133269e8e886 to your computer and use it in GitHub Desktop.
javascript click modal on outside click
//asume all modals have class modal and are closed by removing the class open.
//close open modal on outside click
const clickOutSideModal = (e)=>{
let current = e.target;
let insideModal = false;
while(current.parentNode && !insideModal && current.parentNode.tagName != 'BODY'){
if(current.parentNode.classList.contains('modal')){
insideModal = true;
}
current = current.parentNode;
}
if(!insideModal){ closeOpenModals();}
}
//close modal
const closeOpenModals = ()=>{
[...document.querySelectorAll('.modal')].forEach(modal=>{
modal.classList.remove('open');
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment