const menuItem = document.querySelectorAll(".menu-item");
menuItem.forEach((mi) => {
mi.addEventListener("click", (e) => {
const nextSibling = e.target.nextElementSibling;
nextSibling.classList.toggle("hide");
});
});
function addSubMenuItem(menuItemId, smi) {
const menuItem = document.querySelector(`#${menuItemId}`);
const sibling = menuItem.nextElementSibling;
smi.forEach((subMenuItemName) => {
const li = document.createElement("li");
li.classList.add("sub-menu-item");
li.textContent = subMenuItemName;
sibling.append(li);
});
}
addSubMenuItem("home", ["a", "b", "c"]);
addSubMenuItem("blog", ["a"]);
addSubMenuItem("work", ["a", "b", "c", "d", 1, 24]);
addSubMenuItem("about", ["a", "b", "c", 0, 83, 93]);
.container {
display: flex;
justify-content: space-around;
align-items: center;
position: relative;
background-color: red;
}
.menu-item-container {
display: flex;
justify-content: center;
align-items: center;
position: relative;
}
.menu-item {
padding: 1rem;
cursor: pointer;
user-select: none;
}
ul.sub-menu {
display: inline-block;
list-style-type: none;
top: 100%;
background-color: royalblue;
position: absolute;
padding: 0;
margin: 0;
}
li.sub-menu-item {
padding: .25rem 1rem;
}
.hide {
display: none !important;
}
<div class="container">
<div class="menu-item-container">
<div class="menu-item" id="home">Home</div>
<ul class="sub-menu hide">
</ul>
</div>
<div class="menu-item-container">
<div class="menu-item" id="blog">Blog</div>
<ul class="sub-menu hide"></ul>
</div>
<div class="menu-item-container">
<div class="menu-item" id="work">Work</div>
<ul class="sub-menu hide"></ul>
</div>
<div class="menu-item-container">
<div class="menu-item" id="about">About</div>
<ul class="sub-menu hide"></ul>
</div>
</div>