How can I toggle this dropdown?

yotube
0

Issue

I have tried adding a simple toggle function to the dropdown-btn class which in turn adds the active class (which is set to display: block;) onto the ul class, am I doing anything wrong here?



const dropdown = document.querySelector('.dropdown-btn');

dropdown.addEventListener('click', function() {
dropdown.classList.toggle('active');

});

.sidebar-nav {
display: grid;
gap: 15px;
padding: 15px;
}

.sidebar-nav li {
background: #f0f7ff;
border-radius: 4px;
line-height: 2;
cursor: pointer;
font-weight: 500;
transition: 150ms ease;
position: relative;
}

.options {
display: none;
}

.options.active {
display: block;
}

<nav class="admin-sidebar sidebar">
<div class="sidebar-nav">
<li><a href="#" class="dropdown-btn"><i class="fas fa-address-card"></i><span>Dropdown</span> <i class="fas fa-angle-down"></i></a></li>
<ul class="options">
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
</div>
<nav/>




Solution

When you click on the button you have to toggle the active class on the ul element, wich you have set display:none .



const dropdown = document.querySelector('.dropdown-btn');
const options = document.querySelector('.options');

dropdown.addEventListener('click', function() {
options.classList.toggle('active');

});

.sidebar-nav {
display: grid;
gap: 15px;
padding: 15px;
}

.sidebar-nav li {
background: #f0f7ff;
border-radius: 4px;
line-height: 2;
cursor: pointer;
font-weight: 500;
transition: 150ms ease;
position: relative;
}

.options {
display: none;
}

.options.active {
display: block;
}

<nav class="admin-sidebar sidebar">
<div class="sidebar-nav">
<li><a href="#" class="dropdown-btn"><i class="fas fa-address-card"></i><span>Dropdown</span><i class="fas fa-angle-down"></i></a></li>
<ul class="options">
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
</div>
<nav/>





Answered By - Sfili_81

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top