Context: I’m trying to create a navbar with a sub menu that appears and disappears through hovering.
HTML
<nav>
<div class="logo">
<img src = 'https://cdn.iconscout.com/icon/free/png-256/creative-68-225308.png'>
</div>
<div class="nav-links">
<ul>
<li><a href="#">Home</a></li>
<li class = 'about'>
<a href="#">About</a>
<ul class = 'about-submenu'>
<li><a href="#">Our Team</a></li>
<li><a href="#">Our History</a></li>
<li><a href="#">Our Vision</a></li>
</ul>
</li>
<li class = 'services'>
<a href="#">Services</a>
<ul class = 'svcs-submenu'>
<li><a href="#">Web Design</a></li>
<li><a href="#">Graphic Design</a></li>
<li><a href="#">SEO</a></li>
</ul>
</li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</nav>
CSS
* {
margin: 0;
padding: 0;
}
body {
background-color: rgb(198, 206, 206);
}
.logo img {
width: 3.5rem;
}
nav ul {
list-style: none;
}
nav ul a {
text-decoration: none;
color: black;
}
nav {
display: flex;
justify-content: space-between;
margin: 2rem 15rem 0 15rem;
}
.nav-links ul {
display: flex;
justify-content: space-between;
gap: 4em;
}
ul.about-submenu {
position: absolute;
display: none;
padding: 15px 15px 0px 15px;
margin-top: 10px;
width: 100px;
background-color: azure;
border-radius: 10px;
}
ul.svcs-submenu {
position: absolute;
display: none;
padding: 15px 15px 0px 15px;
margin-top: 10px;
width: 140px;
background-color: aqua;
border-radius: 10px;
}
ul.about-submenu li, ul.svcs-submenu li {
margin-bottom: 15px;
}
ul.about-submenu li a:hover, ul.svcs-submenu li a:hover {
color:brown;
}
Vanilla JavaScript
const about = document.querySelector('.about')
const services = document.querySelector('.services')
const abtDrpdwn = document.querySelector('ul.about-submenu')
const svcDrpdwn = document.querySelector('ul.svcs-submenu')
about.addEventListener('mouseenter', () => {
abtDrpdwn.style.display = 'block'
})
abtDrpdwn.addEventListener('mouseleave', () => {
abtDrpdwn.style.display = 'none'
})
Action: I tried using mouseenter
/mouseover
to make the sub-menu appear, and mouseleave
to make it disappear.
Result: The sub menu appears when I hover over the nav link. The sub menu disappears when I hover out of the sub menu. However, the sub menu doesn’t disappear when you hover out of the nav link.
Expected Result: The sub menu disappears when you hover out of the nav link and sub menu.
Thank you all in advance!