<!--
Forum question answer only:
https://www.sitepoint.com/community/t/capture-ul-tag-under-li-through-js/407291/15
-->
<ul class="nav first">
<li class="lfirst"><a href="">Menu</a></li>
<li class="lfirst">
<a href="#">Menu</a>
<ul class="second">
<li><a href="#">Menu 01</a></li>
<li><a href="#">Menu 02</a></li>
<li><a href="#">Menu 03</a></li>
</ul>
</li>
<li class="lfirst"><a href="#">Menu</a></li>
<li class="lfirst">
<a href="#">Menu</a>
<ul class="second">
<li><a href="#">Menu 01</a></li>
<li><a href="#">Menu 02</a></li>
<li><a href="#">Menu 03</a></li>
</ul>
</li>
<li class="lfirst"><a href="#">Menu</a></li>
</ul>
ul {
margin: 0;
padding: 0;
list-style: none;
}
.first {
display: flex;
position: relative;
z-index: 99;
max-width: 980px;
border: 1px solid #000;
border-right: none;
margin: auto;
background: cyan;
border-bottom: 10px solid red;
}
.first > li {
position: relative;
flex: 1 0 0;
border-right: 1px solid #000;
}
.first a {
padding: 10px;
display: block;
text-decoration: none;
background: cyan;
z-index: 1;
transition: 0.2s ease;
}
.first li:hover > a,
.first a:hover {
background: aquamarine;
}
.first > li > ul {
position: absolute;
left: 0;
top: 0;
right: 0;
z-index: -1;
opacity: 0;
pointer-events: none;
transition: 1s ease;
background: lightblue;
}
.first > li.active > ul,
/*.first > li:hover > ul,*/
.first > li:focus-within > ul {
top: 100%;
margin-top: 1px;
opacity: 1;
pointer-events: initial;
}
.first li ul a {
padding: 5px;
border-bottom: 1px solid red;
}
/* arrows */
.nav li a:first-child:not(:last-child) {
padding-right: 20px; /* make space for arrows*/
}
.nav li a:first-child:not(:last-child):after {
content: "";
position: absolute;
right: 3px;
top: 50%;
margin-top: -6px;
width: 0;
height: 0;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-top: 6px solid red;
transition: 0.5s ease;
}
.nav li:hover a:first-child:not(:last-child):after {
transform: rotate(180deg);
}
/* js adds active class so testing here */
.first > li.active > ul {
box-shadow: 0 0 40px 40px rgba(0, 0, 0, 0.5);
}
/* none of this js is needed as css :hpver can accomplish all this */
const lFirsts = document.querySelectorAll(".lfirst");
lFirsts.forEach((lFirst) => {
lFirst.addEventListener("mouseover", () => {
lFirst.classList.add("active");
});
lFirst.addEventListener("mouseout", () => {
lFirst.classList.remove("active");
});
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.