Home > Blockchain >  How to close navbar when I click outside the navbar?
How to close navbar when I click outside the navbar?

Time:01-15

<span  id="hamburger" onclick="openNav()">
<nav id="nav-bar" >
    <a href="javascript:void(0)"  onclick="closeNav()">&times;</a>
    <ul>
       <li><a href="#">Home</a></li>
       <li><a href="#">Contact</a></li>
       <li><a href="#">About</a></li>
       <li><a href="#">Help</a></li>
       <li><a href="#">Address</a></li>
    </ul>
</nav>
<script>
            navBar = document.getElementById('nav-bar');
            document.onclick = function(clickEvent) {
                if(clickEvent.target.id !== 'nav-bar'){
                    navBar.classList.remove('active');
                }
            }
            function openNav() {
                navBar.classList.toggle('active');
                document.body.style.backgroundColor = 'rgba(0,0,0,0.4)';
            }
            function closeNav() {
                navBar.classList.remove('active');
                document.body.style.backgroundColor = '#fefefe';
            } 
        </script>

Actually, I'm trying to close the navbar when I click outside the navbar. When I call the onclick openNav function, at the same time document.onclick function also called. This will caused my navbar is not opened. The document.onclick function should not call when I call the openNav onclick function. How can I fix this?

CodePudding user response:

            navBar = document.getElementById('nav-bar');
            document.onclick = function(clickEvent) {
              var clickover = clickEvent.target;
                
                if (!document.getElementById('nav-bar').contains(clickover) && clickover.id!="hamburger" ){
                    navBar.classList.remove('active');
                     document.body.style.backgroundColor = '#fefefe';
                }
            }
            function openNav() {
                navBar.classList.add('active');
                document.body.style.backgroundColor = 'rgba(0,0,0,0.4)';
            }
            function closeNav() {
              
                navBar.classList.remove('active');
                document.body.style.backgroundColor = '#fefefe';
            }     
ul li{
  margin:5px;
  display:inline-block;
}

.closebtn{
cursor:pointer;
}
<span  id="hamburger" onclick="openNav()">open Nav</span>
<nav id="nav-bar" >
    <a  onclick="closeNav()">&times;</a>
    <ul>
       <li><a href="#">Home</a></li>
       <li><a href="#">Contact</a></li>
       <li><a href="#">About</a></li>
       <li><a href="#">Help</a></li>
       <li><a href="#">Address</a></li>
    </ul>
</nav>

  • Related