Search code examples
javascriptsimplemodalnodelist

Creating HTML/Javascript Modal with dynamic text


I am learning Javascript and my project contains 3 buttons that open a modal. Everything works fine, however I want to reuse the modal and replace the modal text depending on which button is clicked.

My HTML is below:

    <body>
  <button class="show-modal" id="btn-1">Show modal 1</button>
  <button class="show-modal" id="btn-2">Show modal 2</button>
  <button class="show-modal" id="btn-3">Show modal 3</button>

  <div class="modal hidden">
    <button class="close-modal">&times;</button>
    <h1>Modal Header Content</h1>
    <p class="hidden btn-1 text">
      This is modal 1 text content
    </p>
    <p class="btn-2 hidden text">This is modal 2 text</p>
    <p class="btn-3 hidden text">This is modal 3 text</p>
  </div>
  <div class="overlay hidden"></div>

  <script src="script.js"></script>
</body>

In my Javascript file, I have created variables to access various parts of the HTML:

    // get selector and store in variable for repeated use
const modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const btnCloseModal = document.querySelector('.close-modal');
//since button all have same class of show-modal, have to use querySelectorAll
const btnsOpenModal = document.querySelectorAll('.show-modal');
const text = document.querySelectorAll('.text');
console.log(text);

Then when I click on the button, the modal appears, but I cannot change the text. My thought was to get the button ID (which I get) and if that value is contained in the element class list, then remove the hidden class. But it doesn't work, so there is something I'm not understanding.

    for (let i = 0; i < btnsOpenModal.length; i++) {
  btnsOpenModal[i].addEventListener('click', function () {
    // console.log(btnsOpenModal[i].id);
    console.log(btnsOpenModal[i]);
    let modalText = btnsOpenModal[i].id;

    console.log(modalText);
    if (text.classList.contains(modalText)) {
      text.classList.remove('hidden');
    }

    modal.classList.remove('hidden');
    overlay.classList.remove('hidden');
  });
}

Any help would be appreciated! Perhaps I cannot do this with javascript either, which is fine, but my instinct tell me it can be done.

Thanks!!


Solution

  • The problem with your code is that you are attempting to access the entirety of the querySelectorAll array instead of the individual element that you are interested in. See the code below for an example of a way to resolve this:

    for (let i = 0; i < btnsOpenModal.length; i++) {
      btnsOpenModal[i].addEventListener('click', function () {
        let modalText = btnsOpenModal[i].id;
    
        if (text[i].classList.contains(modalText)) {
          text[i].classList.remove('hidden');
        }
    
        modal.classList.remove('hidden');
        overlay.classList.remove('hidden');
      });
    }