I'm building my first website and I'm having trouble with the click outside modal (nav) to close using javascript.
HTML:
<nav>
<img src="/Images/ham.png" alt="toggle menu" class="menu" id="menu">
</a>
<ul class="show-desktop hide-mobile" id="nav">
<li id="exit" class="exit-btn hide-desktop">
<img src="/Images/exit.svg" alt="exit menu">
</li>
<li><a href="index.html">home</a></li>
<li><a href="work.html">work</a></li>
<li><a href="about.html">about</a></li>
<li><a href="contact.html">contact</a></li>
</ul>
</nav>
Javascript:
<script>
var menu = document.getElementById('menu');
var nav = document.getElementById('nav');
var exit = document.getElementById('exit');
menu.addEventListener('click', function(e) {
nav.classList.toggle('hide-mobile');
e.preventDefault();
});
exit.addEventListener('click', function(e) {
nav.classList.add('hide-mobile');
e.preventDefault();
});
window.onclick = function(event) {
if (event.target == nav) {
nav.classList.toggle('hide-mobile');
e.preventDefault();
}
else if (event.target != nav){
nav.classlist.add('hide-mobile');
e.preventDefault();
}
}
</script>
CSS:
.hide-mobile{
right: -400px;
transition: linear .5s;
}
nav ul {
position: fixed;
width: 60%;
top: 0;
right: 0;
text-align: left;
background: rgb(36,41,44);
height: 100%;
z-index: 7;
padding-top: 3em;
right: 0px;
transition: ease-out .5s;
}
I got the first set of javascript code (menu and exit button functions) from a tutorial and now I'm trying to add the close on outside click function. I've added a window.onclick function to show the nav modal when click on nav and hide it when click outside nav but it wont close when I click outside nav.Any ideas of what I'm doing wrong? Thanks.
var menu = document.getElementById('menu');
var nav = document.getElementById('nav');
var exit = document.getElementById('exit');
menu.addEventListener('click', function(e) {
nav.classList.toggle('hide-mobile');
e.preventDefault();
e.stopPropagation();
});
exit.addEventListener('click', function(e) {
nav.classList.add('hide-mobile');
e.preventDefault();
});
window.onclick = function(event) {
if (event.target != nav){
nav.classList.add('hide-mobile');
event.preventDefault();
}
}
this can solve your problem with your way.
In window.onclick function, you should check is modal open? You can add a specific class when the modal is active and if it is active you can close it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.