i have this code, the js is needed to hide the modal window when the user press the ESC button and when the user click outside the window, the problem is that the function works only for the first modal window and not for the second one, because document.querySelector select only the first div with that class.
Unfortunately when i try to use document.querySelectorAll the function stop working. As you can test with the snippet below.
What should i do? How to use correctly document.querySelectorAll?
function modalClose() {
if (location.hash == '#spedizione-resi' || location.hash == '#soddisfatti-rimborsati') {
location.hash = '';
}
}
// ESC
document.addEventListener('keyup', function(e) {
if (e.keyCode == 27) {
modalClose();
}
});
var modal = document.querySelector('.modal-window');
modal.addEventListener('click', modalClose, false);
modal.children[0].addEventListener('click', function(e) {
e.stopPropagation();
}, false);
.modal-window {
position: fixed;
background-color: rgba(0, 0, 0, 0.65);
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 999999;
opacity: 0;
pointer-events: none;
transition: all 0.3s;
}
.modal-window svg {
width: 30px;
margin: 15px;
fill: #00a5cb;
}
.modal-window:target {
opacity: 1;
pointer-events: auto;
}
.modal-window>div {
width: 90%;
max-width: 600px;
max-height: 400px;
border-radius: 3px;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
padding: 1em;
background: #ffffff;
color: #333333;
text-align: left;
line-height: 1.25em;
}
.modal-window>div>div {
overflow: auto;
max-height: 200px;
}
.modal-window header {
font-weight: bold;
}
.modal-window h1 {
font-size: 150%;
margin: 25px 0px 15px 0px;
color: #333333;
}
.modal-close {
position: absolute;
right: 0;
text-align: center;
top: 0;
}
<div id="spedizione-resi" class="modal-window">
<div>
<a href="#" title="Chiudi" class="modal-close">X</a>
<h1>{{ settings.resi_bar_text }}</h1>
<div>{{ settings.resi_bar_content }}</div>
</div>
</div>
<div id="soddisfatti-rimborsati" class="modal-window">
<div>
<a href="#" title="Chiudi" class="modal-close">X</a>
<h1>{{ settings.rimb_bar_text }}</h1>
<div>{{ settings.rimb_bar_content }}</div>
</div>
</div>
<a href="#spedizione-resi">Modal 1</a>
<a href="#soddisfatti-rimborsati">Modal 2</a>