Hello, Kirupa members.
I need your help.
I have 2 modals on my site ( https://coursuit.netlify.app/ ) You can find them on the right side of the header - “Login modal” (press “Login” button) and “Normal modal” (press “Get Started Button”).
I can close the “Normal modal” on the outside click.
Here is the code:
var btns = document.querySelectorAll(".open-it, .btn-modalclose");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function (e) {
let modal = document.querySelector('.modal')
modal.classList.toggle('show-modal');
window.addEventListener('click', e =>
e.target == modal? modal.classList.remove('show-modal') : false)
e.preventDefault();
});
}
But, I can’t close the “Login modal” on the outside click.
Here is the code:
Could you, please, take a look and tell me what is wrong with the “Login modal” and how can I fix it. Can’t figure it out, the code looks the same to me.
Hi @Helena_G - you’ve run into my personal gripe with the modal capabilities we have natively. Dismissing a modal by clicking outside of the modal area is too difficult to make work.
The main difference is that with Get Started, the modal takes up all available space on the page. This ensures clicking on the empty area catches the appropriate code and closes. Your Login modal only takes up as much space as needed:
If you have a background element on your log-in modal that mimics the same behavior as Get Started where it takes up all available space, your dialog should close appropriately. Hopefully
@kirupa No. I have the same issue very often when I create a similar modal.
And each time I can’t figure out how to close it on outside click.
So, I would be very thankful to get a solution.
Thank you very much in advance
This is going to be a bit hacky, but it hopefully gets you looking in the right direction. The gist is that the top-level element in the modal needs to be 100% of the width. It is this element that detects the click and hides the modal. The contents of the modal are what need to be customized for the type of modal we are dealing with. In this case, the modal needs to be right-aligned.
With all that said, here are the CSS-only changes I made to make this work: