Simple horizontal navigation bar with vanilla js animation


Simple horizontal navigation bar with vanilla js animation Tutorial by Mirko Zovko | 02. Aug. 2020.

How to create horizontal navigation bar with js animation effect

Welcome to one more tutorial in series of creating simple elements with vanilla js. In this tutorial I’ll show you how to create a horizontal navigation bar with js animation effect.

Html structure is very simple with this tutorial:

  • nav - with class menu is container for navigation menu, if you are going to use multiple navigation like this on one page than add one more class that is unique or id and when calling menu function (you will see that later) for element add that class or id
  • m-active - is a div that is used for active and hover effect for the menu. You can call it sliding effect of the menu
  • Menu links are unsorted ul list, and when adding the menu it’s very important to add active class on one of the a tags so that js function know where to start when it’s called

Style for the menu is also not complicated, you can check it below. Only thing that I created a bit advanced is the m-active class. I created after and before pseudo class for it to create an effect of tube for the active part. You can see that in the image below so you will know what I am talking about.

Horizontal menu

To make everything work I created an initMenu function that receives elem parameters. Elem parameter is the container of the menu. I mention that in the beginning, that it would be good to use a unique class or id for this elem.

  • When the function is started it first looks for the active menu link ( a tag with active class ) and adds width and left position of that active link to the m-active div that we are using as indicator of active and hover element. That function is called returnToActiveElement. I add that name to it because we are going to use it more in the next part.
  • Next what I did is get all links and add them to the eventListener for mouse enter and leave and click.
    • When you hover the link it get width and left offset of the menu and add them to the m-active div, so that m-active div come to that hover link
    • when you leave it (on mouseleave) I call function returnToActiveElement so that m-active can go back to the link with class active.
    • when you click on the link it become active
  • I also added eventListener for resize because there is different style properties for smaller screen and because of that I want to refresh the animation to get proper width and left offset of the active element.

Few usage example you can check on jsFiddle or on Codepen

I hope you liked this article. If you have some suggestion or idea feel free to write in comment section bellow. Enjoy! :)