A
A
Andrey Borchik2018-02-08 21:44:55
css
Andrey Borchik, 2018-02-08 21:44:55

How to hide modal (popup) window when clicked away?

There is such a code - when you click on the link, a window appears / disappears.
How to hide modal (popup) window when clicked away?

<li onclick="myFunction()">Цены</li>



<div id="myDIV" style="position: absolute;color: black;left: 428px;width: 226px;top: 36px;padding: 9px 21px;display: none;">
  <a href="/info/kartina-na-holste-cena">Картины на холсте</a><br>
  <a href="/info/flip-flop-cena">Флип-флоп портреты</a><br>
  <a href="/info/portret-maslom-cena">Портреты маслом</a><br>
  <a href="/info/fotooboi-cena">Фотообои</a><br>
  <a href="/info/skinali-cena">Скинали на кухню</a><br>
  <a href="/info/zerkala-dlya-interiera-cena">Зеркала под заказ</a><br>
  <a href="/info/shirokoformatnaya-pechat-cena">Широкоформатная печать</a><br>
  <a href="/info/kupit-kartinu-v-minske-cena"><strong>Все цены</strong></a>
</div>

<script>
function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.style.display === "none") {
        x.style.display = "block";
    } else {
        x.style.display = "none";
    }
}
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Majidov, 2018-02-08
@andryu6ka

You need to either add .overlay above the content of the page but below the modal window and handle the onClick event on it, or handle the click event on any place on the page and check if the click was not on the modal window, then hide this window. Like this:

window.addEventListener('click', function(){
  if (!event.target.closest('#myDIV')) {
    document.getElementById("myDIV").style.display = "none";
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question