Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

    $("#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?

like image 265
amagumori Avatar asked Mar 23 '23 15:03

amagumori


2 Answers

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.

like image 119
Marc Audet Avatar answered Apr 07 '23 07:04

Marc Audet


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

like image 38
DevlshOne Avatar answered Apr 07 '23 09:04

DevlshOne