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?
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/
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With