I am trying to customize the ul inside one of my li elements in the nav by adding a class when hovered. However, I am encountering an issue where the menu disappears when I try to click on it after hovering over it. I want to achieve this functionality using vanilla JavaScript.
document.addEventListener('DOMContentLoaded', function () {
var dropdownItem = document.querySelector('.dropdown-item');
var dropdown = document.querySelector('.dropdown');
dropdownItem.addEventListener('mouseenter', function (e) {
dropdown.classList.add('dropdown-show');
});
dropdownItem.addEventListener('mouseleave', function () {
dropdown.classList.remove('dropdown-show');
})
})
.menu {
list-style: none;
display: flex;
width: 30%;
justify-content: space-between;
align-items: center;
}
.menu li {
position: relative;
}
.menu li a {
color: #999;
text-decoration: none;
}
.menu .dropdown-item {
position: relative;
}
.menu .dropdown-item .dropdown {
position: absolute;
list-style: none;
top: 5px;
padding-top: 40px;
left: -30px;
visibility: hidden;
opacity: 0;
transition: 0.3s;
}
.menu .dropdown-item .dropdown .triangle {
border: 10px solid transparent;
border-bottom-color: #000;
width: 0;
top: 20px;
left: 50%;
transform: translateX(-50%);
position: absolute;
}
.menu .dropdown-item .dropdown.dropdown-show {
opacity: 1;
visibility: visible;
}
.menu .dropdown-item .dropdown li {
background-color: #000;
padding: 10px 20px;
font-weight: lighter;
}
<ul class="menu">
<li class="dropdown-item"><a href="#">About Us</a>
<ul class="dropdown">
<div class="triangle"></div>
<li><a href="#">News</a></li>
<li><a href="#">Our Team</a></li>
<li><a href="#">History</a></li>
</ul>
</li>
<li><a href="#">Gallery</a></li>
<li><a href="#">Contact</a></li>
</ul>