04 August 2020   |   by Pratyush Aswal   |   Coding, Blogs

Simple side navigation bar using HTML, CSS and JS

Navigation bars are a must in every website. Now lets get straight to building a simple side navigation bar.

1. HTML – We need division structure of the webpage.

This is the structure of the divisions in the webpage. We make a division with id “header” which is the top bar. The top bar contains the button (icon) which toggles the sidebar in and out. We set the class of the button to inactive which we will see in CSS section.
Second division is with id “content”. Content div contains two divisions:

  • “nav” division which is our sidebar.
  • “main” division which will contain our content of the website.
Note: We have used icon from fontawesome. To use this icon you need to include this in you header section:

CSS – Now we do some styling and add some important classes.

Here we set the positions and dimensions of the divisions defined in the HTML section. Now lets look at some important classes/id.

  • #nav: We give it z-index 5 and position fixed so that it can glide over other divisions and can act as side navbar.
  • .hide : we give it a left margin of -210px to make it go out of the screen therefore hiding the navbar.
  • .show : we give it left margin of 0px to show it on the web page.
  • .inactive: we give this class to button(icon) when navbar is hidden. It changes its colour to white.
  • .active: we give this class to button(icon) to change its colour to some colour other than white.
  • .rotate: we give this class to button(icon) to rotate it 90degrees to show the transition of sidebar.
  • .rotateback: we give this class to button(icon) to rotate it -90degrees to show the transition of sidebar while hiding.

JavaScript: Now we have all the required divisions and classes, let us build the functionality.

  • We call the function “func()” at the click of the button(icon). It takes two elements: 1. Division –“nav” (side navbar) and 2. Icon
  • It stores the sides of the “nav” div with the help of function “getBoundingClientRect()”.
  • It checks if the navbar is hidden or not. If hidden already – It adds show class and removes hide class from “nav” and sets rotate and active class to icon.
  • If “nav” is not hidden – It adds hide class from “nav” also removing show class. It adds rotateback class and inactive class while removing rotate and active classes from icon.

Therefore, we have created a toggle function of the side navbar. This ends the creation of simple side navigation bar.