0
votes

I'm trying to make a show/ hide menu button for mobile devices using media queries.

I'm aware that CSS3 on mobile is faster, most of the time, on mobile compared to using jQuery animate because of hardware acceleration, hence I want to use this method.

I need a smooth, 0.5s CSS3 animation from 0px to whatever height the container is.

What I'd like to do - or the logic I'd thought of so far - is when clicking this UI icon, you toggle the height of the .nav>ul from 0px to auto.

I've tried using transition: height and adding a class to the required bit using jQuery, but I cannot figure out how to apply a CSS£ transform / transition to the height and get it to smoothly toggle the height, and I'm now stuck. Don't even know what to Google for (have tried, trust me!).

Here's a working JSFiddle: http://jsfiddle.net/3v47n/ - the small grey 20x20 icon is the trigger.

My jQuery:

$('.nav span').on('click',function(){

    $('.nav ul').addClass('animateHeight')

});

And my CSS:

.nav {
min-height: 60px;
}
.nav ul {
height: 0;
overflow: hidden;
transition: height 0.5s ease;
}
.nav ul.animateHeight {
height: auto;
max-height: 9999px;
}
2
You cannot transition to :auto; you'll have to use jquery slideUp() slideDown() or set a fixed height in pixels to transition to, or use some kind of tricky trick stackoverflow.com/questions/3508605/… - Jonas Grumann
Thanks @JonasGrumann I've tried doing that - but it won't work. It's been a long time since I worked with CSS3 animations / transitions so i've no idea if my CSS is even correct. - tjcss

2 Answers

2
votes

Just found a solution for you, maybe not the best solution, but a workaround.

As you can't transition to height: auto you could transition the max-height. But you need to set the target height to a value which is close to height: auto, but always a big bigger.

See here: http://jsfiddle.net/3v47n/5/

.nav ul {
  max-height: 0;
  overflow: hidden;
  transition: max-height 2s ease;
}
.nav ul.animateHeight {
  max-height: 999px;
}
1
votes

Looking at your code this could be your best solution I think, please use this jQuery below in your code:

$('.nav span').on('click',function(){
    if($('.nav ul').hasClass('animateHeight')){
        $('.nav ul').removeClass('animateHeight');
    } else {
        $('.nav ul').addClass('animateHeight');
    }
});