Search code examples
javascriptcssfunctionpopupdisplay

error with the modal pop up window closing up with onclick event javascript


Trying to handle the popup window closing up. But I'm having an error. Is the issue reffered to the rhis keyword ?

https://codesandbox.io/s/tours-test-slick-v1uw96?file=/index.js:626-1309

// Get the modal
const modal = document.getElementById("myModal");

// Get the button that opens the modal
const btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
const close = document.getElementsByClassName("closeBtn");

// When the user clicks the button, open the modal
btn.onclick = function () {
  modal.style.display = "block";
};

// When the user clicks on <span> (x), close the modal
close.onclick = function () {
  modal.style.display = "none";
};

// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
  if (event.target == this.modal) {
    modal.style.display = "none";
  }
};


Solution

  • You are trying to get the close button by classname, this returns an array with all the elements so, you need to be especific with the button.

    You can use const close = document.getElementsByClassName("closeBtn")[0]; or set an id to the button instead