Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making navbar collapse with JS

Currently my navbar shrinks with the page size, using @media screen. This works fine, but when the page is very small I want the navbar to collapse into a vertical drop down which requires a click to open.

Due to my circumstances I cannot use bootstrap, just html/css and js.

example on jsfiddle

like image 603
Charlie Avatar asked Dec 06 '25 18:12

Charlie


1 Answers

first hide the nav bar element using @media and change elements into list view

@media screen and (max-width: 850px){
  //replace max width with your width

  ul li {
    display: block;
  }
  ul {
    display: none;
  }


}

Showmenu functions toggles the visibility of nav bar's elements

function showmenu()
{
    var x = document.getElementById('myUL');
    if (x.style.display == 'none') {
        x.style.display = 'block';
    } else {
        x.style.display = 'none';
    }
}

Also add a button to trigger the function

<!DOCTYPE html>
<html lang="en">

<head>
<button onclick = 'showmenu();'>click me to see menu</button>
  <ul id='myUL'>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
  </ul>
</head>


</html>

Hope this helps

like image 93
Aman Jain Avatar answered Dec 08 '25 07:12

Aman Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!