Xtian
Xtian

Reputation: 3587

animating an element's height using jquery

I have some bars that are filled with a height %, but right when the page loads I would like all the bars to fill up and then decrease to 0. I know how to fill it up with a for loop:

for(i = 1; i <= 100; i++)

but to have a it come back down

for(i = 100; i == 100; i--)

I'm just not sure how to put them together to make the variable i go to 100 then decrease back down to 0?

Upvotes: 0

Views: 133

Answers (7)

Devin Burke
Devin Burke

Reputation: 13820

You're looking for:

for(i = 100; i >= 0; i--)

But you could just do this slideUp:

$('someElement')
    .hide()
    .slideDown(500, function () {
        $(this).slideUp(500);
    });

The above would animate the element like you want. That code equates to roughly the following, in case you even want to do more complicated animate animations:

$('someElement')
   .hide()
   .animate({ height: '100%' }, 500, function () {
        $(this).animate({ height: 0 }, 500);
    });

Update: Here is a jsFiddle demonstration.

Upvotes: 6

Jesse van Assen
Jesse van Assen

Reputation: 2290

I think jQuery animate is what you are looking for. Result is something like this.

Upvotes: 0

mildog8
mildog8

Reputation: 2154

dude slideToggle. Check it - http://jsfiddle.net/6hp2G/. works like a boss

Upvotes: 0

Michiel van Oosterhout
Michiel van Oosterhout

Reputation: 23094

You can do it all in one loop:

for(var i = 0; i <= 200; i++) {
    var height = (i <=100) ? i : 200 - i;
}

The variable height will go from 0 to 100 and then back to 0.

Upvotes: 1

Jasper
Jasper

Reputation: 76003

If you are trying to animate the height of an object then I think you want the .animate() function of jQuery:

$('.bar-elements').animate({ height : '100%' }, 1500, function () {
    $(this).animate({ height : 0 }, 1500);
});

or alternatively you can use the slideUp/slideDown functions that do this already:

$('.bar-elements').hide().slideDown(1500, function () {
    $(this).slideUp(1500);
});

Docs for .animate(): http://api.jquery.com/animate

Docs for .slideUp(): http://api.jquery.com/slideup

Upvotes: 0

Vishwanath Dalvi
Vishwanath Dalvi

Reputation: 36671

How about this:

for(i = 100; i >= 0; i--)

Upvotes: 0

danwellman
danwellman

Reputation: 9273

the second one should be:

for(i = 100; i >= 0; i--)

Upvotes: 0

Related Questions