0

I have looked throught at least 10 threads here and I didn't find the solution. What I'm trying to do is change the height property with transition which is supposed to be triggered by my JavaScript code. That doesn't happen though.

nav {
    background: rgb(242, 242, 242);
    border-radius: 0px 0px 15px 15px;
    display: none;
    height: 0px;
    margin-top: 68px;
    overflow: hidden;
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 1;
    transition: height 1s ease;
}



var button = document.getElementsByTagName('button')[0];
var image = document.getElementsByTagName('img')[0];
var bar = document.getElementById('bar');
var nav = document.getElementsByTagName('nav')[0];
var clicks;

button.onclick = function() {
    if (clicks <= 0 || clicks === undefined || clicks === null) {
        nav.style.display = 'block';
        nav.style.height = 'auto';
        bar.style.borderRadius = '0px';
        image.src = 'assets/image/chevron-up.png';
        clicks++;
    }
    else {
        nav.style.display = 'none';
        nav.style.height = '0px';
        bar.style.borderRadius = '0px 0px 15px 15px';
        image.src = 'assets/image/menu-three-horizontal-lines-symbol.png';
        clicks = 0;
    }

}

Why? How do I fix this?

4
  • 1
    the auto value isn't animatable. Commented Aug 5, 2019 at 21:59
  • Still doesn't seem to work after changing it to 62px, for example. Commented Aug 5, 2019 at 22:01
  • and also, the issue is from changing the display property as it's not animatable thus no transitions occurs. Commented Aug 5, 2019 at 22:05
  • Yes, the display property is what caused the issue. Thanks for pointing it out. Commented Aug 5, 2019 at 22:19

1 Answer 1

1

Since the auto value is not animatable, try setting the height of the nav to a fixed value via it's scrollHeight property instead, then it will animate:

nav.style.height = nav.scrollHeight + 'px';

Also, since you use overflow: hidden you don't really need to toggle the display value, and can simple toggle the height value, see this isolated example: https://jsfiddle.net/andreekeberg/xt4pazfd/

Sign up to request clarification or add additional context in comments.

4 Comments

Works perfectly but the magic stops after the first click. The height just changes without any transition again.
See my update, this is because of display not being animatable either.
I'm going to play with the code, I hope it works! Thank you!
Works perfectly! Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.