How to make smooth opening dropdown with basic javascript code?

Viewed 379

How can I make the red backgrounded "Content" area open smoothly from top to bottom when click to "Clicker" with this piece of code? And extra question is, how can I add more Clickers in the same Html with the same javascript code? If I duplicate these, only one is working.

function myFunction() {
  var x = document.getElementById("myLinks");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
.accordion {
    position: relative;
    width: 100%;
    height: auto;
    background:red;
}.grider{
    display: block;
    width: 100%;
    background: #fff;
}

#myLinks {
display:none;
}

.content {
height:50px;}
<div class="accordion">
<a href="javascript:void(0);" onclick="myFunction()" class="grider clearfix toggle">    
<span>Clicker</span>
 </a>


<div class="content clearfix" id="myLinks">Content</div>
</div>

1 Answers

You don't need Javascript for all animations. Why don't you try with CSS?

const btns = document.querySelectorAll('.btn-dropdown')

btns.forEach(btn => {
  btn.addEventListener('click', function(e) {
    e.target.classList.toggle('open')
  })
})
html,
body {
  margin: 0;
  font-family: Arial;
}

nav {
  display: flex;
}

.btn-dropdown {
  position: relative;
  cursor: pointer;
  padding: 8px 16px;
  border: 1px solid gray;
}

.dropdown-content-container {
  overflow-y: hidden;
  max-height: 0;
  transition: all 0.25s;
}

.btn-dropdown.open>.dropdown-content-container {
  max-height: 120px;
  transition: all 0.4s;
}
<nav>
  <div class="dropdown-wrapper">
    <div class="btn-dropdown">
      CLICK 1
      <div class="dropdown-content-container">
        <div class="dropdown-content">
          DROPDOWN CONTENT 1
        </div>
      </div>
    </div>
  </div>
  <div class="dropdown-wrapper">
    <div class="btn-dropdown">
      CLICK 2
      <div class="dropdown-content-container">
        <div class="dropdown-content">
          DROPDOWN CONTENT 2.1<br /> DROPDOWN CONTENT 2.2<br /> DROPDOWN CONTENT 2.3<br /> DROPDOWN CONTENT 2.4<br />
        </div>
      </div>
    </div>
  </div>
</nav>

Related