I created a toggle-menu, as shown in this demo.
I addded a css transition effect for div.nav-menu, and i used max-height:0; to max-height:480px;.
When I click the menu toggle to show the menu, the transition works well. But when I click the menu toggle to hide the menu again the transition doesn't work.
What did I do wrong?
You are wrong about CSS Transitions. They do not animate when you add or remove class, It will only animate when you change the CSS properties. And You are directly adding and removing classes.
Here is your solution:
$( '.menu-toggle' ).on( 'click', function() {
if(nav.hasClass('toggled-on')) {
menu.css('maxHeight', 0);
//^ Here is changed the 'max-height` first so that the
// Transition animation will trigger first
}
else menu.css('maxHeight', '480px');
// ^ If not I changed it back to 480px;
} );
// Next I bind on the transaction end event of the element to toggle class
// After it finishes the transistion
menu.on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function() {
nav.toggleClass( 'toggled-on' );
});
Updated Fiddle
There is a much easier way to get the effect you're after.
Working Example
js
$(function() {
$('.menu-toggle').click(function(){
if($('.nav-menu').is(':hidden')){ // check to see if menu is hidden
$('.nav-menu').slideDown();} // if so slide down
else{$('.nav-menu').slideUp();} // else slide up
});
});
css
html {
font-size: 100%;
overflow-y: scroll;
}
body {
max-width: 860px;
margin: 0 auto;
font-family: Helvetica, sans-serif;
}
.main-navigation {
clear: both;
min-height: 45px;
margin-top: 30px;
position: relative;
}
.menu-toggle {
cursor: pointer;
display: inline-block;
font: bold 16px/1.3;
margin: 0;
padding: 10px;
color: #fff;
background-color: #1e1e1e;
}
.nav-menu {
margin: 0;
background-color: #1e1e1e;
display: none;
overflow: hidden;
}
.nav-menu ul {
display: block;
margin: 0;
padding: 0;
width: 100%;
}
.nav-menu li {
display: block;
padding: 10px;
}
.nav-menu li a {
display: block;
padding:10px;color:#fff;line-height:1;
text-decoration: none;
}
.nav-menu li a:hover,.nav-menu li a:focus{background:#272727;}
.toggled-on li a:active{background:#2A8A15;}
API for .slideUp() and API for .slideDown()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With