0

I am making a popup modal box using only HTML, JS, and CSS. It does everything right but I also want it to close when clicking anywhere outside the box.

In my HTML doc I have a simple button to show contacts that provide a modal window:

<div class="card">
    <div class="card__controls">
        <a class="card__button button-open">Show Contacts</a>
    </div>
</div>

<section class="modal">
    <div class="modal__content">
        <span class="close modal__button button-close" type="button">&times;</span>
        <h2 class="visually-hidden">Contacts</h2>
        <h3>Address:</h3>
        <p>Saint-Petersburg</p>
    </div>
</section>

And here is my simple JS code for it:

var popup = document.querySelector('.modal');
var openPopupButton = document.querySelector('.button-open');
var closePopupButton = popup.querySelector('.button-close');

openPopupButton.addEventListener('click', function(evt) {
    evt.preventDefault();
    popup.style.display = "block";
})

closePopupButton.addEventListener('click', function() {
    popup.style.display = "none";
})

document.addEventListener('keydown', function(evt) {
    console.log("keydown in listener: ")
    if (evt.keyCode === 27) {popup.style.display = "none"}
})

I think I can somehow define if I am clicking on a modal window or not using:

target.className == "modal"

However, I can't find the solution on how to use it in an appropriate way.

What should I add to my JS file to close the modal section by clicking outside it?

  • 3
    Does this answer your question? [How do I detect a click outside an element?](https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element) – kmoser Dec 02 '20 at 18:30
  • You're already handling `keydown` events that happen to the `document. Just set up another `document` event handler for `click` that hides the modal. – Scott Marcus Dec 02 '20 at 18:36
  • There is "onblur" event which can help you with this – Aleksandar Dec 02 '20 at 18:58

0 Answers0