The Issue
I'm looking to implement a flexible javascript solution to opening and closing multiple modal windows on the same page.
I have found way to open multiple modal windows in such a manner, but I can't for the life of me figure out how to close them by the click of a button or by clicking outside of the modal window itself.
Here is my javascript code:
var openModal = document.getElementsByClassName("open-modal");
for (var i = 0; i < openModal.length; i++) {
var thisOpenModal = openModal[i];
thisOpenModal.addEventListener("click", function() {
var modal = document.getElementById(this.dataset.modal);
modal.style.display = "block";
}, false);
}
(I didn't write this code myself, it's an edited copy of "pgk's" answer over on this page: Opening multiple modal boxes on one page)
I trigger the modal windows by adding the 'open-modal' class to my "buttons" and I use 'data-modal' in relation to the id's of the modal windows:
<div class="featurette-wrap featurette--anchor open-modal" data-modal="modal-microsoft-account">
Opprett konto
</div>
The button above triggers the modal window with the id of modal-microsoft-account:
<div class="modal" id="modal-microsoft-account">
Microsoft-konto
</div>
So my question is:
How can I implement a way to close a modal window once it's opened?
I've tried doing this, but I can't get it to work (from W3schools):
// When the user clicks on <span> (x), close the modal
closeModal.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";
}
}