views:

53

answers:

2

On a site I'm making I need to have a progress bar, I found one that suited my needs. By default it will incrementally change the color when a certain percentage is reached (0-30 red, 30-70 orange, etc). My only problem is changing them, I can set them easily with a static number such as 50, but when I try to do it dynamically (ie: 2000*.3 = 600) it fails. I don't know much js/jquery so this is especially difficult for me, if you could help that would be great. I'm pretty sure it's something really simple I'm missing.

The code that Fails:

var barmax = 2000;
var orangeBound = Math.round(barmax * .3);
var greenBound  = Math.round(barmax * .7);
//alert(orangeBound+":"+greenBound);
$("#pb1").progressBar({ max: barmax, textFormat: 'fraction',
barImage: {
       0: 'images/progressbg_red.gif',
       orangeBound: 'images/progressbg_orange.gif',
       greenBound: 'images/progressbg_green.gif'}
    });

The code that works but I can't use because it has to be dynamic:

$("#pb1").progressBar({ max: barmax, textFormat: 'fraction',
    barImage: {
       0: 'images/progressbg_red.gif',
       600: 'images/progressbg_orange.gif',
       1400: 'images/progressbg_green.gif'}
    });

If you need to see the source, here. Thanks again!

+3  A: 

In JS, {orangeBound: "foo"} will just result in a key called "orangeBound" containing the value "foo". You'll have to build the object separately:

var barImages = {0: 'images/progressbg_red.gif'};
barImages[orangeBound] = 'images/progressbg_orange.gif';
// ...
$(...).progressBar({..., barImage: barImages});
Matti Virkkunen
Thank you. That saved me a lot of time.
Lienau
+1  A: 

The problem is that using orangeBound as the key in the object literal means that the string "orangeBound" is used, rather than the value of the variable. Instead, try building the object like so:

var barImage = {0: 'images/progressbg_red.gif'};
barImage[orangeBound] = 'images/progressbg_orange.gif';
barImage[greenBound] = 'images/progressbg_green.gif'
var barmax = 2000;
var orangeBound = Math.round(barmax * .3);
var greenBound  = Math.round(barmax * .7);
$("#pb1").progressBar({
    max: barmax,
    textFormat: 'fraction',
    barImage: barImage
});
Michael Williamson