July 8, 2013

CSS Transitions Not working after toggleClass()

85Ryan’s Question:

I created a toggle-menu, like the DEMO.

I add a css transition effect for div.nav-menu , and i used max-height:0; to max-height:480px; .

When click the menu toggle to show the menu, the transition was working good. But when I click the menu toggle to hide the menu again the transition didn’t work now.

What did I did 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
    nav.toggleClass( 'toggled-on' ); //Then only I toggled the class
} );

Updated Fiddle

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!