A
A
Alex_js2020-05-02 17:00:02
css
Alex_js, 2020-05-02 17:00:02

How to hide menu when hovering over menu items?

Good afternoon.
I want to make dropdown menus on mouse hover.

The task is to make it so that when hovering over the span, the menu itself appears.
And it closed back when the mouse cursor went out of the div block.

Here are my efforts. The menu seems to appear, but disappears immediately when the cursor is displayed outside the span. I want to make it so that it disappears only at the moment when the cursor is outside the entire block.


let clickOnMe = document.querySelector('span');
let menu = document.querySelector('ul');
clickOnMe.onmouseover = function () {
menu.classList.remove('menu');
menu.classList.add('menuOpen');
}

let div = document.querySelector('div');
div.onmouseout = function() {
menu.classList.remove('menuOpen');
menu.classList.add('menu');
}

Below is the HTML and CSS

HTML code

<div>
     <span>Click to show menu</span>
          <ul class="menu">
      <li>Раздел 1</li>
      <li>Раздел 1</li>
      <li>Раздел 1</li>
      <li>Раздел 1</li>
    </ul>
  </div>


css

div {
margin: 0 auto;
width: 200px
height: 120px;
border: 1px solid black;
}

.menu {
display: none;
}

.menuOpen {
background: grey;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tranceinheart, 2020-05-02
@Tranceinheart

The easiest option is to put ul.menu inside the span itself.

.menu {
display: none;
}
span:hover .menu{
display:block;
}

In this case, you won't have to use the JS script at all
If you want to leave everything as it is
let clickOnMe = document.querySelector('span');
let menu = document.querySelector('ul');
clickOnMe.onmouseover = function () {
menu.classList.remove('menu');
menu.classList.add('menuOpen');
}

let div = document.querySelector('div');
div.addEventListener("mouseout", function(e){
  if(e.target == div){
      menu.classList.remove('menuOpen');
      menu.classList.add('menu');
    }
}, false)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question