Toggle div height in jQuery

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

I mentioned this earlier question addressing the same issue :

I noticed that one of the answers 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 structure to anything other than jQuery 1.4.4, the div immediately disappears as soon as the page loads. This is a problem that I experienced in my project.

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

+4
source share
3 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 the best way to code this type of animation. I just demonstrated how to fix the error.

Note that this use of .toggle is deprecated since jQuery 1.8.
Link: http://api.jquery.com/toggle-event/

Why do I need a block

Some of the other solutions include the jQuery .height() function, which returns a pixel value without a unit. In this case, the computed value is forcibly / excellent is the pixel value, so the unit "px" is not required.

In the original example, the .height() function was not used, so you had to specify the units for them to work.

+3
source

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

+3
source

Is that what you are going to do?

http://jsfiddle.net/mmDCk/

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

This will switch the height to 40 or 10 depending on what is currently located.

+1
source

Source: https://habr.com/ru/post/1499266/


All Articles