Question

I need to take a percentage value, convert it to pixels and move a div upwards using JQuery animate for a progress bar I'm trying to build. The div containing the graphic that needs to move upwards has a 268 pixel height (so that is our 100%).

as an example, I put 38% as the starting percentage value that I need to convert to a pixel value and move div with the id prog_anim to that number of pixels upwards (should be around 101 pixels)

var result = 38 / 100 * 268;
function bgr_animate(result) {
    $('#prog_anim').animate({
    'marginTop' : result
    });
}

and then I have the following link on a button that performs the action:

a href="javascript:;" onclick="bgr_animate(result)"

being a total Javascript noob I have no idea where the above syntax is wrong. Can anyone correct me here? Thanks!

Was it helpful?

Solution

Try this:

function bgr_animate(percent, height) {
    var pixels = percent / 100 * height;
    $('#prog_anim').animate({
        'marginTop' : pixels
    });
}

And your button;

<a href="javascript:;" onclick="bgr_animate(30, 268)">

OTHER TIPS

I see a few areas for improvement.

Instead of hardcoding 268, use var graphicHeight = $("#prog_anim").outerHeight();.

You'll need to reverse the direction of the margin top since you want it to move up. marginTop is one way to do that, but setting a CSS position: absolute; and using top instead of marginTop would be better.

So:

var result = -(38 / 100 * graphicHeight);

Try this out

$('#prog_anim').animate({
      height: result
      top:-=resultInc
      }, 5000, function() {
     alert("Animated");
});     

Where resultInc is the number of pixels by which it grows

Using this you can move upwards and increase the height downwards giving the impression that it grew upwards

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top