Direct link to a modal window doens't work

Viewed 57

For this webpage: https://www.wonderewereldvan.be/VakantieinBelgie/KalenderTest2.html I would like have a direct link to a modal popup.

Off course I searched Stackoverflow for possible solutions, and I tried several ones. However when using https://www.wonderewereldvan.be/VakantieinBelgie/KalenderTest2.html#myModal it doesnt't open the modal window.

The last piece of code I tried was

    function popModal() {
      // code to pop up modal dialog
    }

    var hash = window.location.hash;
    if (hash.substring(1) == 'myModal') {
      popModal();
    }

Those are the details of the popup:

<div class="modal" id="myModal">

The code I found on W3Schools

    <script>
// Get the modal
var modal = document.getElementById("myModal");

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

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// 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
span.onclick = function() {
  modal.style.display = "none";
}

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

Many thanks in advance for your help!

1 Answers

You can put the existing code into an event handler named hashchange :

window.addEventListener("hashchange", () => {
  var hash = window.location.hash;
  if (hash.substring(1) == "myModal") {
    popModal();
  }
});

Read more about this handler in MDN hashchange

Related