DEV Community

David Frempong
David Frempong

Posted on

How I built a megamenu feature with Vanilla JavaScript

On one of the projects I'm working on, I want the visitor to be able to hover on a nav menu item, and a megamenu will appear. Here's how I built it.

After styling everything in CSS, I gave the original class in CSS a display: none. Then, I created another duplicate class with an ending (-visible) (example: .thisdiv and .thisdiv-visible) and gave it a display: block.

 .navmenucontent{
  display: none;
  }

 .navmenucontent-visible{
  display: block;
  }
Enter fullscreen mode Exit fullscreen mode

Next, I went to JavaScript and created my variables. I then targeted the menu item itself (let's say "shop"), and gave it an EventListener of click. This lets the browser listen for a click, and then do something.

I then created another EventListener that said that if the mouse left that div, to remove the div. This event is 'mouseleave'.

From there I created a function that basically said: "When this menu item is clicked, show this menu-content, and if the mouse leaves, hide it." Here's how I built this feature.

 let navhover = 
 document.getElementsByClassName('navhover') 
 [0]



 let newselections = 
 document.getElementsByClassName('navhover', 
 'new', 'selections')[1]

 let menuitemnew = 
 document.getElementsByClassName('nav- 
 hover', 'new')[0]




 let showitemnew = function () {
 {
    newselections.classList.add('navhover', 
       'new', 'selections-visible')
    navhover.classList.add('navhover- 
       visible')
       console.log('showing')
     }
 }

 let hideitemnew = function () {
   {
 newselections.classList.remove('navhover', 
      'new', 'selections-visible')
    navhover.classList.remove('navhover- 
      visible')
    console.log('removed')
    }
  }



 menuitemnew.addEventListener('mouseover', 
    function () {
    showitemnew();
 })


newselections.addEventListener('mouseleave', 
   function () {
   hideitemnew();
 })
Enter fullscreen mode Exit fullscreen mode

One thing I learned from this: Organize both your CSS and your JavaScript, because it's very easy to get things confused.

Top comments (0)