JMay
JMay

Reputation: 361

Drop down menu effects

I have this drop down menu that appears when a button is clicked and disappears when clicked again. I'm wondering how to make the menu disappear from the bottom up, instead of just instantly disappear. I'm not asking for the exact code, just need pointed in the right direction. Thank you.

let nav = document.querySelector("nav");
let icon = document.querySelector(".mobile-icon");
console.log(nav);
icon.addEventListener("click", showMenu);

function showMenu() {
if (nav.style.display == "none"){
nav.style.display = "block";
} else {
    nav.style.display = "none";
}

}

Upvotes: 2

Views: 77

Answers (2)

Naren Murali
Naren Murali

Reputation: 56886

Here is my solution, you cannot use transition for height property hence we use max-height. The problem is we need to set height in px for this solution to work, hence please use this workaround and test!

let nav = document.querySelector("nav");
let icon = document.querySelector(".mobile-icon");
icon.addEventListener("click", showMenu);
nav.querySelector("ul").style.margin = "16px 0px";
nav.style.maxHeight = nav.querySelector("ul").clientHeight + 32 + "px";
function showMenu() {
  nav.classList.toggle("hideThis");
}
nav{
  transition: max-height 0.5s ease-out;
  height:auto;
  overflow:hidden;
}
nav.hideThis{
  max-height:0px !important;
}
<button class="mobile-icon">toggle</button>
<nav>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
</ul>
</nav>

Upvotes: 1

Steven
Steven

Reputation: 131

My solution would be to create a class that sets the hight of the menu to 0px and then toggle this on and off using JavaScript.

I have created a small mockup in JSFiddle with some comments on the important parts.

Link to JSFiddle is - https://jsfiddle.net/gmuz2m98/

Here is the code though:

HTML -

<button> Hide/Show </button>

<ul>
  <li> Link 1 </li>
  <li> Link 2 </li>
  <li> Link 3 </li>
  <li> Link 4 </li>
</ul>

CSS -

ul {
  /* Give the ul a transition to run smoothly */
  transition: all .5s;
  list-style:none;
  padding:0;
  margin:20px 0px;
  background-color:#D6D6D6;

  /* Make sure overflow is hidden so when the hight is droped to 0px the li elements stay hidden */
  overflow:hidden;

  /* Give the ul a default hight to revert to, without this the transiton won't work */
  height:160px;
}

li {
  padding: 10px 20px;
}

/* This is the class that will be added with JavaScript */
.hide {
  height:0px;
}

JS -

// Assign the ul and the button to a variable
var ul = document.getElementsByTagName('ul')[0],
        btn = document.getElementsByTagName('button')[0];

// Create a function that lets the class 'hide' be toggled on and off the ul
function dropDown(){
    ul.classList.toggle('hide');
}

// Assign the function to the button with an EventListener
btn.addEventListener('click',dropDown,false);

Upvotes: 2

Related Questions