简体   繁体   中英

Modal window close on clicking outside

I am new to JavaScript, so I need an explanation of how the code is working. In w2Schools there is a modal window code https://www.w3schools.com/howto/howto_css_modals.asp , in which there is a function -

// When the user clicks anywhere outside of the modal, close it

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

How is it working? function(event) defines where event happens,click event happens on window, so why event.target is being checked whether the event happens on modal? I mean why are we not checking if event.target is if outside modal or if(event.target!==modal) ?

I suggest you to use dev tools all the time when you are stuck. That's how I improved myself on html elements when I was a beginner in that too. I'll make it clear for you with the help of pictures.

As we already know what modal is by var modal = document.getElementById("myModal"); we need to click div with id myModal. And thats the one picture. 在此处输入图像描述

To make it even more clear for you, I've clicked background-color property to make see where exactly is #myModal . As you can see here, whenever user clicks on this black space. The modal will be closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM