Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67411

How to run the same JS script in one HTML file?

$
0
0

I have a JS script that opens a modal dialog window when you click on a certain HTML element.

My problem is that the script only works for one element. When I call the same class name .trigger on another element, the entire script fails to work.

HTML

<div class="trigger">
   <h2>Contact Me Form</h2>
      <div class="modal">
          <div class="modal-content">
              <span class="close-button">x</span>
              <p>Contact form details goes here</p>   
          </div>
       </div>
</div>

<div class="trigger">
   <h2>About Me</h2>
      <div class="modal">
          <div class="modal-content">
              <span class="close-button">x</span>
              <p>About Me details goes here</p>   
          </div>
       </div>
</div>

JS

          var modal = document.querySelector(".modal");
          var trigger = document.querySelector(".trigger");
          var closeButton = document.querySelector(".close-button"); 

          function toggleModal() {
              modal.classList.toggle("show-modal");
          }

          function windowOnClick(event) {
              if (event.target === modal) {
                  toggleModal();
              }
              else if (event.target === closeButton) {
                toggleModal();
              }
          }

          trigger.addEventListener("click", toggleModal);
          closeButton.addEventListener("click", toggleModal);
          window.addEventListener("click", windowOnClick);

edit: I tried to change my JS code and it still doesn't work:

          var modals = document.querySelectorAll(".modal");
          const triggers = document.querySelectorAll('.trigger');
          var closeButtons = document.querySelectorAll(".close-button"); 

        for (const trigger of triggers) {
             trigger.addEventListener('click', toggleModal);
          }

          function toggleModal(event)
            event.target.querySelector('.modal').classList.toggle("show-modal");
          }

          function windowOnClick(event) {
              if (event.target === modal) {
                  toggleModal();
              }
              else if (event.target === closeButton) {
                toggleModal();
              }
          }


          closeButton.addEventListener("click", toggleModal);
          window.addEventListener("click", windowOnClick);
    ```

Viewing all articles
Browse latest Browse all 67411

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>