Reputation: 43
I would like to hide a dropdown after I select something from it, but keep it there for me to hover over again later.
My current code:
<div class="navbutton_container">
<button onclick="someFunction()"><p>Title</p></button>
<div class="nav_dropdown">
<button onclick="someFunction()"><p>Content1</p></button>
<button onclick="someFunction()"><p>Content2</p></button>
<button onclick="someFunction()"><p>Content3</p></button>
<button onclick="someFunction()"><p>Content4</p></button>
</div>
</div>
.navbutton_container > .nav_dropdown {
display: none;
opacity: 0;
}
.navbutton_container:hover > .nav_dropdown {
display: block;
opacity: 1;
position: absolute;
}
After I select any button in this, I would like the dropdown to temporarily disappear so it's out of the way until they stop hovering over it. After they move off, I would like it so they could move back on and have the :hover property to work again.
If you think there's a better structure, I'm 100% open to changing it!
Upvotes: 0
Views: 87
Reputation: 23654
Here's a method that will use a combination of adding classes and detecting mouseouts to acheive the goal
function someFunction() {}
window.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.navbutton_container').forEach(el => el.addEventListener('mouseover', e => {
let targ = e.target.classList.contains('navbutton_container') ? e.target : e.target.closest('.navbutton_container');
targ.querySelector('.nav_dropdown').classList.remove('hold');
}))
document.addEventListener('click', e => {
if (e.target.closest('.nav_dropdown')) {
e.target.closest('.nav_dropdown').classList.add('hold')
}
})
})
.navbutton_container>.nav_dropdown {
display: none;
opacity: 0;
}
.navbutton_container:hover>.nav_dropdown {
display: block;
opacity: 1;
position: absolute;
}
.navbutton_container:hover>.nav_dropdown.hold {
display: none;
opacity: 0;
}
<div class="navbutton_container">
<button onclick="someFunction()" class='toggler'><p>Title</p></button>
<div class="nav_dropdown ">
<button onclick="someFunction()"><p>Content1</p></button>
<button onclick="someFunction()"><p>Content2</p></button>
<button onclick="someFunction()"><p>Content3</p></button>
<button onclick="someFunction()"><p>Content4</p></button>
</div>
</div>
<div class="navbutton_container" style='margin-top:100px'>
<button onclick="someFunction()" class='toggler'><p>Title</p></button>
<div class="nav_dropdown ">
<button onclick="someFunction()"><p>Content1</p></button>
<button onclick="someFunction()"><p>Content2</p></button>
<button onclick="someFunction()"><p>Content3</p></button>
<button onclick="someFunction()"><p>Content4</p></button>
</div>
</div>
Upvotes: 1