Making navbar collapse with JS


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 ( == 'none') { = 'block';
    } else { = 'none';

Also add a button to trigger the function

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

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


Hope this helps

Author by


Updated on December 03, 2022


  • Charlie
    Charlie 6 months

    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

    • viCky
      viCky over 5 years
      Hi Charlie. This is not a complete question. There is not enough detail regarding what you have tried or implemented. I would request you to do a basic research and try to implement something first. When you are not able to implement any thing, then come to us with details of the issues that you are facing. This will enable us better to help you. See the How to Ask page for help clarifying this question.
    • Charlie
      Charlie over 5 years
      I have tried, every single example of this i can find uses bootstrap, obviously because it's easier but due to my circumstances i cannot use bootstrap. Having a thread like this, with an answer on how to preform this task without bootstrap would be very useful to alot of people in my situation
  • Charlie
    Charlie over 5 years
    Thanks, but unfortunately i need a solution that doesnt use boot strap