Home > front end >  How can I toggle this dropdown?
How can I toggle this dropdown?

Time:05-23

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

<nav >
  <div >
    <li><a href="#" ><i ></i><span>Dropdown</span><i ></i></a></li>
    <ul >
      <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');

});

CodePudding user response:

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 >
  <div >
    <li><a href="#" ><i ></i><span>Dropdown</span><i ></i></a></li>
    <ul >
      <li>Option 1</li>
      <li>Option 2</li>
      <li>Option 3</li>
    </ul>
  </div>
  <nav/>

  • Related