Hello! Situation: there is a one-page page, among which there are 5 absolutely identical blocks with a button (the button has the same class - .btn_sign). Pressing the button should invoke a modal window.

I can not figure out how to make each of the .btn_sign buttons invoke the .modal-window_entry window. So far, I am only learning the basics of JS, so I'm dumb. Help me please)

Below is the code that calls the modal window by pressing only the first button.

var openModalEntry = document.querySelector(".btn_sign"); var showModalEntry = document.querySelector(".modal-window_entry"); var closeModalEntry = showModalEntry.querySelector(".close-entry"); openModalEntry.addEventListener("click", function(event) { event.preventDefault(); showModalEntry.classList.add("show-entry"); }); closeModalEntry.addEventListener("click", function(event) { event.preventDefault(); showModalEntry.classList.remove("show-entry"); }) 

    2 answers 2

    You can create a loop that creates a function for each button:

     var openModalEntry = document.querySelectorAll(".btn_sign"); var showModalEntry = document.querySelectorAll(".modal-window_entry"); var closeModalEntry = document.querySelectorAll(".close-entry"); for(var i = 0; i < openModalEntry.length; i++){ openModalEntry[i].addEventListener("click", function(event) { event.preventDefault(); showModalEntry[0].classList.add("show-entry"); }); }; for(var i = 0; i < closeModalEntry.length; i++){ closeModalEntry[i].addEventListener("click", function(event) { event.preventDefault(); showModalEntry[0].classList.remove("show-entry"); }); }; 
     div.modal-window_entry {display:none;} div.modal-window_entry.show-entry {display:block;} 
     <button class="btn_sign">Показать 1</button> <button class="btn_sign">Показать 2</button> <button class="btn_sign">Показать 3</button> <div class="modal-window_entry">Текст <button class="close-entry">Закрыть</button></div> 

      Once you have several buttons with one class, you need to use querySelectorAll , it finds all the buttons with a class, and querySelector only the first.

       var openModalEntry = document.querySelectorAll(".btn_sign"); openModalEntry.forEach(function(button) { button.addEventListener("click", function(event) { event.preventDefault(); console.log(this.innerHTML); }) }); 
       <div class="btn_sign">111</div> <div class="btn_sign">222</div> <div class="btn_sign">333</div> 

      • Thanks for the answer. For some reason, this particular option did not work. Apparently, some kind of mistake was made, now it works - uncle acid