Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I toggle this dropdown?

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?

https://jsfiddle.net/q45yc3vt/10/

HTML

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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/>

CSS

  .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;
}

JS

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

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

});

>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/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading