I am facing an issue with a dropdown menu in my webpage. The menu is initially hidden, but should become visible when the list element containing it is clicked. I have written JavaScript code to add a class that changes the visibility property to visible upon clicking. However, the problem I encountered is that the visibility only changes for a brief moment and then reverts back to hidden. How can I modify the code so that the dropdown menu remains visible after the initial click until the next one?
document.querySelector('#drop').addEventListener('click', (e) => {
document.querySelector('.sub-men').classList.toggle('visible');
})
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
nav {
display: flex;
flex-direction: row;
justify-content: space-between;
height: 10vh;
background-color: aquamarine;
}
.logo {
display: flex;
align-items: center;
margin-left: 10px;
}
.main-menu {
display: flex;
list-style: none;
align-items: center;
}
.main-menu > li {
position: relative;
height: 10vh;
}
.main-menu > li > a {
display: flex;
padding: 0 1rem;
text-decoration: none;
background-color: antiquewhite;
height: 10vh;
align-items: center;
}
.sub-men {
display: flex;
flex-direction: column;
position: absolute;
list-style: none;
visibility: hidden;
}
.sub-men > li {
position: relative;
background-color: aquamarine;
padding: .5rem 1rem;
width: 100px;
text-align: center;
}
.visible {
visibility: visible;
}
.sub-men > li:hover {
background-color: aqua;
}
.sub-men > li > a {
text-decoration: none;
position: relative;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="styles.css">
<script src="jquery-3.6.0.min.js"></script>
</head>
<body>
<nav>
<h1 class="logo">Logo</h1>
<ul class="main-menu">
<li><a href="">Link 1</a></li>
<li><a href="" id="drop">Link 2</a>
<ul class="sub-men">
<li><a href="">Sub-1</a></li>
<li><a href="">Sub-1</a></li>
<li><a href="">Sub-1</a></li>
</ul>
</li>
<li><a href="">Link 3</a></li>
</ul>
</nav>
<script src="index.js"></script>
</body>
</html>