I am new to web development and trying to create a portfolio website. I am trying to create a full-page nav bar. I am using bootstrap 5 and the navbar works when I click the button on the right, but I want to auto close the navbar when a menu item is selected. I am creating everything in one body with different sections.
HTML
<nav class="navbar fixed-top navbar-expand-lg">
<div class="container">
<a onclick="openMenu();" title="" class="btn">
<span></span>
<span></span>
</a>
<div class="menu">
<ul class="menu_list">
<li class="menu_list">
<a href="#home" title="" onclick="closeMenu();" class="menu_link">Home</a>
</li>
<li class="menu_list">
<a href="#about-me" title="" onclick="closeMenu();" class="menu_link">About</a>
</li>
<li class="menu_list">
<a href="#projects" title="" onclick="closeMenu();" class="menu_link">Projects</a>
</li>
<li class="menu_list">
<a href="#contact" title="" onclick="closeMenu();" class="menu_link">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
CSS
.btn{
position: absolute;
top: 21px;
right: 25px;
z-index: 3;
display: flex;
width: 20px;
height: 20px;
}
/*size of the button lines*/
.btn span{
position: absolute;
display: flex;
width: 20px;
height: 2px;
background: rgba(247,72,78,255);
transition: .5s;
}
/*position of each line within the button space*/
.btn span:nth-child(1){
top: 25%;
}
.btn span:nth-child(2){
top: 75%;
}
.btn.is-active span{
background: rgba(247,72,78,255);
}
/*transformation to X*/
.btn.is-active span:nth-child(1){
top: 50%;
transform: rotate(-45deg);
}
.btn.is-active span:nth-child(2){
top: 50%;
transform: rotate(45deg);
}
/*menu details*/
.menu {
background: rgb(0, 0, 0,0.60);
display: flex;
align-items: center;
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
padding: 100px;
z-index: 1;
transform: .5s;
opacity: 0;
visibility: hidden;
}
/*when active (clicked)*/
.menu.is-active{
transition: .5s;
opacity: 1;
visibility: visible;
}
javascript: open menu() works fine, it’s used when the menu is open or closed using btn. The closeMenu() is what I am having difficulty with. I try to make the selection and toggle back to .menu from is-active but it does not work.
function openMenu(e){
let menu = document.querySelector('.menu');
let btn = document.querySelector('.btn');
menu.classList.toggle('is-active');
btn.classList.toggle('is-active');
e.preventDefault();
}
function closeMenu(){
let menu = document.querySelector('.menu.is-active');
let btn = document.querySelector('.btn.is-active');
menu.classList.toggle('.menu');
btn.classList.toggle('.btn');
e.preventDefault();
}
Any help is appreciated.