Thank you for sharing!
There's a way to do it without using JavaScript, handling the menu visibility with CSS.
If you add a <div> containing only the hamburger button and the menu, you can use the :focus-within CSS pseudo-selector. :focus-within applies to an element if it has the focus, but also if one of its children is focused.
For example, if you write the HTML for the menu like this:
Now, the <nav class="navbar"> will initially remain hidden, but it will appear when any child of <div class="menu-container"> is focused. For example, when you click on the hamburger button or some of the menu items.
I love to create responsive data driven web apps with intuitive user experiences. When not writing code, I spend my time immersed in dance, aerial arts, and learning spoken languages.
Location
NYC
Education
City College of New York - B.A. in Advertising and Public Relations
This is a cool solution i just tried out in my own code! Thanks for sharing! The only downside is once the menu is open, you have to click outside the hamburger to close it which from a user experience perspective could confuse a user for a second/ make them think your site has a bug. Unless you also have a work around to this that i am missing.
Thank you for sharing!
There's a way to do it without using JavaScript, handling the menu visibility with CSS.
If you add a
<div>containing only the hamburger button and the menu, you can use the:focus-withinCSS pseudo-selector.:focus-withinapplies to an element if it has the focus, but also if one of its children is focused.For example, if you write the HTML for the menu like this:
You can use the
:focus-withinselector like this:Now, the
<nav class="navbar">will initially remain hidden, but it will appear when any child of<div class="menu-container">is focused. For example, when you click on the hamburger button or some of the menu items.Hey thank u so much for sharing this man! Will try this
This is a cool solution i just tried out in my own code! Thanks for sharing! The only downside is once the menu is open, you have to click outside the hamburger to close it which from a user experience perspective could confuse a user for a second/ make them think your site has a bug. Unless you also have a work around to this that i am missing.
why not this about leaving it go home :) :
=== CSS ===
.show {
display: block; /* Show navbar when class 'show' is added */
}
=== JS ===
you toggle it first with showNavbar(), then :
function hideNavbar() {
const navbar = document.getElementById('navbar');
navbar.classList.remove('show');
}
const navbar = document.getElementById('navbar');
navbar.addEventListener('mouseleave', hideNavbar);