For my responsive design project, I am implementing a menu that switches to a menu button when the width is less than or equal to 768px.
Currently, I am using jQuery to dynamically adjust the height of the menu when the menu button is clicked. The jQuery script adds style="height: 152px;"
to the nav
element, while CSS3 with
transition: height 0.35s ease 0s;
ensures smooth sliding animation.
Everything works smoothly until I resize the window while the menu is displayed. When the width > 768px
, the menu items are floated horizontally on the same line instead of stacking vertically below each other.
The issue arises from the fact that even though the menu is no longer needed, it maintains a height of 152px, creating unnecessary space below it.
I have attempted to find a listener that can detect when the menu button becomes hidden (display: none;
) so that I can remove the inline style, but so far, I have not been successful.
If anyone has a straightforward solution to this problem, any help would be greatly appreciated.
// CSS
.nav-collapse {
overflow: hidden;
transition: height 0.35s ease 0s;
}
@media (max-width: 768px){
.collapse { height:0; }
}
// JS
$('.btn-navbar').click(function(){
var nav = $('.nav-collapse');
if($(nav).hasClass('collapse')){
$(nav).height($(nav).find('ul').height());
$(nav).removeClass('collapse');
} else {
$(nav).attr('style','');
$(nav).addClass('collapse');
}
});
// HTML
<nav class="nav-collapse collapse">
<ul>
<li> menu items </li>
</ul>
</nav>