Answer the question
In order to leave comments, you need to log in
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>
Answer the question
In order to leave comments, you need to log in
The easiest option is to put ul.menu inside the span itself.
.menu {
display: none;
}
span:hover .menu{
display: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.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 questionAsk a Question
731 491 924 answers to any question