skriverswe
skriverswe

Reputation: 3

Delay in hover on sub menu

I want a sub menu to be able to be shown when the cursor is hovered over but at the moment the sub menu is closed once the mouse is hovered over any link.

Here is the code

HTML

<div class="body">
    <div class="menu">HOVER HERE</div>
    <ul class="drop-down">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    </ul>
</div>

CSS

.body {
  width: 400px;
  margin: 0 auto;
  margin-top: 30vh;
  font-family: Lato, sans-serif;
}
.menu {
  display:block;
  border: 1px solid #000;
  width: 150px;
  background: #000;
  color:#FFF;
  padding: 15px;
  text-align:center;
}
ul li {
  border: 1px solid #000;
  width: 150px;
  padding: 15px;
  list-style:none;
  text-align:center;
}
ul {
  margin: 0;
  padding: 0;
}
.drop-down {
  display:none;

}
.open {
  display:block;
}

JavaScript

document.addEventListener('DOMContentLoaded', function () {
    var dropdownItem = document.querySelector('.menu');
    var dropdown = document.querySelector('.drop-down');

    dropdownItem.addEventListener('mouseenter', function (e) {
        dropdown.classList.add('open');
    });
    dropdownItem.addEventListener('mouseleave', function () {
        dropdown.classList.remove('open');
    })
})

Codepen is here

https://codepen.io/Kenneman/pen/yLLPmeX

Upvotes: 0

Views: 279

Answers (1)

isherwood
isherwood

Reputation: 61133

This problem has been solved a thousand times on SO, and virtually every CSS-only menu demonstrates how it's done. The submenu must be inside the hovered element. No JavaScript is necessary:

.menu:hover ul {
    display: block;
}

Demo

You'll have to fiddle with styling to get the submenu background fixed, but that's the idea.

Upvotes: 1

Related Questions