amagumori amagumori - 1 month ago 5x
CSS Question

Toggling height of div in jQuery

This question has been already addressed, but none of the solutions have worked for me.

I referred to this earlier question addressing the same problem:

I noticed that one of the responses gave this jsfiddle link, which implements the exact functionality that I want, and works.


But when I changed the framework to anything but jQuery 1.4.4, the div starts instantly disappearing as soon as the page loads. This is the problem I've been having on my own project.

Any ideas on how to get that jsfiddle working on jquery 2.x? What am I missing?


The fix is simple:

$("#topbar").toggle(function () {
        height: "40px"
    }, 200);
}, function () {
        height: "10px"
    }, 200);

You just need to add px units to the height value.

See demo at:


Some of the other posted answers show a better way of coding this type of animation. I simply demonstrated how to fix the bug.

Note that this use of .toggle has been deprecated since jQuery 1.8.

Why The Unit is Needed

Some of the other solutions involve the jQuery .height() function, which returns a unit-less pixel value. In this case, the computed value is coerced/cast to be a pixel value, so the 'px` unit is not required.

In the original example, the .height() function was not used so the units needed to be specified to make things work.