Question

I can't for some reason make a smooth div, I'm trying to make it expand and contract when I click a button, but it doesn't work.

Javascript:

function expandContract(id) {
    var object = document.getElementById(id);
    if (object.style.height != "0px") {
        object.style.height = "0px";
    } else {
        object.style.height = object.scrollHeight;  
    }
}

HTML:

<div id='test' style='overflow:hidden;'>
Test pest fest.
</div>
<button onClick='expandContract("test");'>Expand/Contract</button>

jsFiddle

I've also tried setting it do max-height, but still I can't get it to expand again. How would I do this without any javascript plugins?

Was it helpful?

Solution

You're missing +"px". You are required to set a unit (em, px, %, etc) when using style.height. Because scrollHeight gives you just a numeric value, you must append the units which are px in this case.

function expandContract(id) {
    var object = document.getElementById(id);
    if (object.style.height != "0px") {
        object.style.height = "0px";
    } else {
        object.style.height = object.scrollHeight+"px";  
    }
}

jsFiddle

OTHER TIPS

I got it to work in Chrome, as is. IE when I changed the 'overflow' to 'scroll'.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top