How do I make this code close
a modal
when user clicks outside of the modal window both on iOS and non-touch devices?
I know about some other similar topics here regarding window.onclick
and touch
devices, but I'm relatively new to JS and I don't know how to properly combine this function (for both platforms).
var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
var closeModal = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
window.addEventListener('click', closeModal);
window.addEventListener('touchend', closeModal);
.modal {
display: none;
position: fixed;
overflow: hidden;
left: 0;
bottom: 0;
width: 100%;
height: auto;
background-color: black;
color: white;
font-size: 100%;
}
.close {
color: white;
float: right;
font-size: 70%;
}
.close:hover, .close:focus {
color: #000;
text-decoration: none;
}
<div id="myModal" class="modal">
<span class="close">×</span>
<p>Some content here</p>
</div>