I'm trying to create a mobile menu using jQuery, but I'm having the following issue: mobile menu is only being displayed based on width I put @ media query, and when I click at one of the navigation links, they disappear as they should. But if I resize the window for full width, the navigation bar is completely hidden, and I can only see the logo. For the navigation menu to show up again I have to refresh the page. How can I fix that?
Here's the HTML for header
<header>
<div class="logo">
<i class="fas fa-code fa-3x"></i>
</div>
<div class="mobile-menu"><i class="fa fa-bars fa-2x"></i></div>
<nav class="navbar">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
CSS for mobile-menu
and media-query for both mobile-menu
and navbar
.mobile-menu {
color: white;
position: absolute;
right: 20px;
display: none;
}
@media only screen and (max-width: 768px){
.mobile-menu {
display: block;
}
.navbar {
display: none;
flex-direction: column;
background: var(--secondary);
width: 11rem;
position: absolute;
right: 0;
top: 60px;
}
}
JS
$('.mobile-menu').on('click', function () {
$('.navbar').slideToggle();
});
$('.navbar').click(function () {
$(this).hide();
});
The reason of the nav menu is not being shown as you resize back the window is that you call hide() method that adds inline (display: none) css style to your element. To prevent that, I would advice you to add/remove additional css class to your navbar.
For example:
.hidden {
display:none;
}
@media only screen and (max-width: 768px){
.hidden {
display:block; // Or whatever (flex, grid, etc.)
}
}
Or:
Remove use show() at navbar at resize breakpoint.
$(window).resize(function () {
var width = $(this).width()
if (width > 768) {
$(".navbar").show()
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.