How I built a megamenu feature in Vanilla JavaScript

On a recent project, I wanted the visitor to be able to hover on a menu item, and a megamenu would appear. Here's how I did it.

After building and styling it in CSS, I gave the class in CSS a display: none;. Then, I created another class called (-visible) and gave it a display: block. Here's an example of how I did it.

  .navmenucontent{
   display: none;
   }

  .navmenucontent-visible{
  display: block;
  }

What I did next was go to JavaScript and create 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();
})