Everyone is here

var modalz = document.getElementById('myModal'); var btn = document.getElementById("myBtn"); var spa = document.getElementsByClassName("close")[0]; btn.onclick = function() { modalz.style.display = "block"; } spa.onclick = function() { modalz.style.display = "none"; } window.onclick = function (event) { if (event.target == modalz) { modalz.style.display = "none"; } } var two = document.getElementById('two'); var raz = document.getElementById("raz"); var spaned = document.getElementsByClassName("close")[0]; raz.onclick = function(e) { two.style.display = "block"; e.stopPropagation(); } spaned.onclick = function() { two.style.display = "none"; } window.addEventListener ('click', function (event) { if (event.target != two.querySelector(".modal-content")) { two.style.display = "none"; } }); 
 .modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.8); } .modal-content { background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; } .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; } 
  <button id="myBtn">Open modal</button> <div id="myModal" class="modal"> <div class="modal-content"> <span class="close">&times;</span> <p> modal hui</p> </div> </div> <script src="script.js"></script> <button id="raz">Open modal</button> <div id="two" class="modal"> <div class="modal-content"> <span class="close">&times;</span> <p> modal 2</p> </div> </div> <script src="script1.js"></script> 

    3 answers 3

    I propose this option to work with modal windows, it is more optimal than that presented in the question. Comments of his work are in the JS code:

     //Находим все тэги button, в которых присутствует атрибут data-target let buttons = document.querySelectorAll('button[data-target]'); //Находим все модальные окна let modals = document.querySelectorAll('.modal'); //Находим все кнопки с классом close, которые лежат внутри "модального" элемента let close = document.querySelectorAll('.modal .close') //Здесь создаем массив, в котором будут храниться элементы, по нажатию на которые у нас не будет срабатывать событие window.click let noPropagation = [...buttons, ...modals]; //Здесь в массиве будут лежать все элементы, по нажатию на которые у нас закрываются все модальные окна: window и кнопки close, можно добавлять и другие элементы в этот массив let closeEvents = [window, ...close]; //Создаем функцию, которая убирает все активные модальные окна let removeActive = () => { modals.forEach(el => { el.classList.remove('active') }) } //Здесь мы запрещаем срабатывания события click, при которых у нас закрываются модальные окна, подробнее читаем про event.stopPropagation() noPropagation.forEach(item => { item.addEventListener('click', (e) => { e.stopPropagation(); }) }) //Здесь отрабатывается закрытие модальных окон при нажатии на window и close "кнопки" closeEvents.forEach(item => { item.addEventListener('click', (e) => { removeActive() }) }) //Здесь привязываем событие, при которых срабатывает вызов модального окна buttons.forEach(button => { button.addEventListener('click', (e) => { //Читаем атрибут data-target, который должен равняться id нашего модального окна let target = e.target.getAttribute('data-target') removeActive(); document.getElementById(target).classList.add('active') }) }) 
     * { box-sizing: border-box; } .modal { position: fixed; left: 0; right: 0; margin: auto; width: 300px; height: 300px; border: 1px solid #333; display: none; } .modal.active { display: block; } .modal .close { cursor: pointer; } 
     <button data-target="modal-1">Open modal 1</button> <div id="modal-1" class="modal"> <div class="contmod"> <span class="close">&times;</span> <p> modal 1</p> </div> </div> <button data-target="modal-2">Open modal 2</button> <div id="modal-2" class="modal"> <div class="contmod"> <span class="close">&times;</span> <p> modal 2</p> </div> </div> 

      Because, as I answered you in your previous question, the scope of the variables that you declare is global, that is, the whole page.

      Hmm, the question has changed, but it's nothing.

      Because, as I answered you in your previous question,

      "The second file overlaps ... window.onclick from the first."

      Use addEventListener .

      • But please, please, a more accurate record, apparently in my case I have written something wrong and it still does not work. - Erik Spichak
      • or is there some alternative for using a window? - Erik Spichak
      • window.addEventListener ('click', function (event) {if (event.target == two) {two.style.display = "none";}}) Something is not so written:? - Erik Spichak
      • if (event.target != two) {... - Igor
      • one
        On the modal windows you need to hang stopPropagation (), then the "common events" will not be passed on click on the modal window. - NeedHate

      Here is a fixed example for your code:

       var modalz = document.getElementById('myModal'); var btn = document.getElementById("myBtn"); var spa1 = document.getElementsByClassName("close")[0]; var spa2 = document.getElementsByClassName("close")[1]; var mod_cont1 = document.getElementsByClassName("modal-content")[0]; var mod_cont2 = document.getElementsByClassName("modal-content")[1]; var mod_class = document.getElementsByClassName("modal")[0]; btn.onclick = function() { modalz.style.display = "block"; } spa1.onclick = function() { modalz.style.display = "none"; } spa2.onclick = function() { two.style.display = "none"; } mod_cont1.onclick = function (event) { event.stopPropagation(); } mod_cont2.onclick = function (event) { event.stopPropagation(); } modalz.onclick = function(event){ modalz.style.display = "none"; } var two = document.getElementById('two'); var raz = document.getElementById("raz"); var spaned = document.getElementsByClassName("close")[0]; two.onclick = function(e){ this.style.display = 'none'; } raz.onclick = function(e) { two.style.display = "block"; e.stopPropagation(); } 
       .modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.8); } .modal-content { background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; } .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; } 
       <button id="myBtn">Open modal</button> <div id="myModal" class="modal"> <div class="modal-content"> <span class="close">&times;</span> <p> modal hui</p> </div> </div> <script src="script.js"></script> <button id="raz">Open modal</button> <div id="two" class="modal"> <div class="modal-content"> <span class="close">&times;</span> <p> modal 2</p> </div> </div> 

      I took 2 of your classes for modal-content and prevented the event from surfacing for them. and you had another error, you did not attach a handler to the cross of the second modal window. to close the window.

      • Thanks for the clarification, but I also saw the mistake - Erik Spichak