Plamen Dobrev
Plamen Dobrev

Reputation: 73

JavaScript doesn't trigger CSS transition

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?

Upvotes: 0

Views: 97

Answers (1)

Andr&#233; Ekeberg
Andr&#233; Ekeberg

Reputation: 367

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/

Upvotes: 1

Related Questions