Hamburger Menu: HTML, CSS & JavaScript

Let’s make a very simple but, responsive hamburger menu with HTML, CSS, and pure JavaScript. If you have been looking for a tutorial on how to create hamburger menu with HTML, CSS, and Vanilla JavaScript. This post is going to be helpful for you.

HTML code for Hamburger Menu

Go ahead and launch your favorite text editor, and create an html file the following html code within a basic HTML5 skeleton and finally save the file with fine name and .html tag.

<header>
  <h1>Logo..</h1>
</header>

<nav>
  <div class="tootle-menu" >
    <h1 id="toggle-bar">
      ☰
    </h1>
  </div>
  <ul class="mainMenu">
	<li><a href="index.html">Home</a></li>
	<li><a href="test.html">Test</a></li>
	<li><a href="#">Services</a></li>
	<li><a href="#">Blog</a></li>
	<li><a href="#">Portfolio</a></li>
  </ul>
</nav>	

CSS Media Query code for Hamburger Menu

The code that you see below is the actual meat of me the hamburger menu, I explicitly did not include the styling part of the CSS code.


@media (max-width: 768px){
	.mainMenu{
		display: none;
	}

	.mainMenu.hamburger{
		display: block;
	}

}


@media (min-width: 769px){
	.mainMenu{
		display: initial;
	}

	#toggle-bar{
		display: none;
	}

}

CSS Media Query Explained…

@media (max-width: 768px)

This part of css is executed when user’s screen size is 768px or below. Here we are hiding the .mainMenu at screen size 768px and below. And displaying hamburger icon as a block element with CSS, and by adding (toggle) .hamburger class with JavaScript click event.

@media (min-width: 769px)

This CSS media query is executed as soon as, the user’s screen reaches 769px and beyond. Here we are hiding the hamburger icon, putting .mainMenu in the initial stage for big screen.

JavaScript code for Hamburger Menu

function toggleMenu() {
  let getMenu = document.querySelector(".mainMenu");
  getMenu.classList.toggle("hamburger");
}
let getHamburger = document.querySelector("#toggle-bar");

getHamburger.addEventListener("click", toggleMenu);

JavaScript Code Explained…

With the help of JavaScript, we are just adding “hamburger” class to the “.mainMenu” with a click event.

Click event is triggered when hamburger icon or the hamburger element block is clicked or tapped.

As soon as, click event is triggered .hamburger class is added to the mainMenu and made visible with the help of CSS media query. And when any <li> element is clicked from the mainMenu, the .hamburger class gets removed and mainMenu child elements disappear.

For add and remove class functionality, we are using JavaScript classList.toggle method.

Find the Hamburger menu minimal html, css, and javascript code on one html file from github gist

Code URL :
https://gist.github.com/aks84/ad753069a4c12ea357983b6f0df38f77

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.