Steve G.
Steve G.

Reputation: 409

CSS height not transitioning in Javascript

help me out here with why my CSS transition isn't working.

I'm trying to animate a height change to a <div> element, either growing it or shrinking it, through a Javascript function. My markup is this:

<div class="post series expandcollapse" id="id1" style="height: 32px;">
    <p class="expandcollapse_link" id="expandcollapselink1" name="expandcollapselink1" onclick="toggleCollapsedItem('1');"><img id="expandcollapseimage1" name="expandcollapseimage1" class="expandcollapse" src="images/icons/expandcollapse.png" alt=""></p>
    <h2 onclick="toggleCollapsedItem('1');">Some random heading here</h2>
    <p>Some random text here</p>
</div>

The CSS attached to the <div>, <h2>, and <img> are:

div.expandcollapse { border-bottom-left-radius: 20px; border-bottom-right-radius: 20px; height: 32px; transition: all 5s ease-in; overflow: hidden; }
div.expandcollapse h2 { cursor: pointer; }
div.expandcollapse img.expandcollapse { transition: all .5s; cursor: pointer; }
div.expandcollapse p.expandcollapse_link { float: right; margin-top: -2px; }

When the user clicks on this, it launches this Javascript function:

function toggleCollapsedItem(clickedItem, forceOpen = false) {
    var collapsedItem = document.getElementById('id' + clickedItem);
    var collapsedLink = document.getElementById('expandcollapselink' + clickedItem);
    var collapsedImage = document.getElementById('expandcollapseimage' + clickedItem);
    if(typeof collapsedItem.originalHeight === 'undefined') {
        Object.defineProperty(collapsedItem, 'originalHeight', { value: collapsedItem.style.height, writable: false });
    }
    if((collapsedItem.style.height === collapsedItem.originalHeight) || (forceOpen === true)) {
        collapsedItem.style.height = 'auto';
        collapsedImage.style.transform = 'rotate(45deg)';
    } else {
        collapsedItem.style.height = collapsedItem.originalHeight;
        collapsedImage.style.transform = '';
    }
}

The image rotates gradually (according to the transition) exactly as it should, but the height doesn't care about the transition. Can anyone spot my problem here? I've been up and down Google, Stackoverflow for similar questions, all over the place, and I can't get the height to change gradually.

Thanks, everyone.

Upvotes: 0

Views: 49

Answers (1)

connexo
connexo

Reputation: 56753

You cannot transition to or from auto values, only between defined values.

I'm assuming the element can be of varying height. If you're already using Javascript, you can transition from 32px to the element's offsetHeight.

So instead

collapsedItem.style.height = 'auto';

you'd do

collapsedItem.style.height = collapsedItem.offsetHeight+'px';

Upvotes: 1

Related Questions