Toggling height of div in jQuery

12,768

Solution 1

The fix is simple:

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

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

See demo at: http://jsfiddle.net/audetwebdesign/3dd3s/

PS

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.
Reference: http://api.jquery.com/toggle-event/

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.

Solution 2

jQuery

$("#topbar").click(function () {
    $(this).animate({
        height: ($(this).height() == 40) ? 10 : 40
    }, 200);
});

CSS

#topbar {
    background: orange;
    color: white;
    display:block;
    width:100%;
    text-align:center;
    height:40px;
}

HTML

<div id='topbar'>toggle me</div>

jsFiddle

Solution 3

Is this what you're going for?

http://jsfiddle.net/mmDCk/

$("#topbar").click(function() {
    $(this).animate({
        height: ($(this).height() == 10) ? 40 : 10
    }, 200);
});

That will toggle the height to either 40 or 10 depending on what it is at the moment.

Share:
12,768

Related videos on Youtube

amagumori
Author by

amagumori

Updated on September 15, 2022

Comments

  • amagumori
    amagumori about 1 year

    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.

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

    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?