Alex Stanese
Alex Stanese

Reputation: 775

Progressbar with color transition jquery?

Hello I'm trying to create a progressbar in wich on the click event it decreases in percentage (with a small animation) and changes its color from green to red. So the first color is 100% green. If I press once, the width should be 99% and the color a little bit more to red. This should continue till width of inner progressbar is 1% and the color is 100% red.

Is that possible? Or I have to set some limits where the color changes to another one? I will only use jquery and jquery mobile. (NO jquery-ui)

I have this so far:

css:
#battery{
    height: 100%;
    margin-left: 2%;
    margin-top: 1%;
    border-color: black;
    border-style: solid;
}

#battery-inner{
    background:green;
    height: 100%;
    float: right;
    width: 100%;
}

js (wich is included on the desired onclick() function):

$bar.css("width", 100 * parseFloat($bar.css('width')) / parseFloat($bar.parent().css('width')) -10 + '%');

I want the colors to be like in this example (red side, yellow middle, green other side)

http://www.cssflow.com/snippets/animated-progress-bar/demo

So far it works but it doesn't have any animation and also no color change...

Upvotes: 0

Views: 2918

Answers (1)

SW4
SW4

Reputation: 71150

FIDDLE

This uses a small slider plugin I wrote in jQuery, but should give you a good idea of how this can be accomplished.

The trick is simply to work out the % value of the progress bar then apply this to an RGB color, inversely for the RED component, progressively for the GREEN.

HTML

<div id='slider' class='sliderBar'></div>
<button>Remove 10%</button>

CSS

html, body {
    height:100%;
    width:100%;
    margin:0;
    padding:0;
}
#slider {
    height:20px;
    max-height:20px;
}
.sliderBar-progress {
    background:rgb(0, 255, 0);
}

jQuery

$('#slider').sliderBar({
    start: 100,
    onChange: function (val) {
        var red = 0,
            green = 0;
        if (val >= 50) {
            red = 255 - Math.round(((val - 50) / 50) * 255);
            green = 255;
        } else {
            red = 255;
            green = Math.round(((val) / 50) * 255);

        }
        $('.sliderBar-progress').css({
            background: "rgb(" + red + "," + green + ",0)"
        });
    }
});

$('button').on('click', function () {
    $('#slider').setsliderBar($('#slider').getsliderBar()-10, true);
});

Upvotes: 2

Related Questions