Progress Bar

A progress bar that dynamically changes color

by mlms13

HTML

<div id="progress">
    <div id="completed"></div>
</div>
<button id="plus">+</button> <button id="minus">-</button>

CSS

#progress {
    border: 1px solid #ccc;
    margin: 24px 24px 6px;
    padding: 3px 4px;
    width: 400px;
}
#completed {
    height: 16px;
    width: 0;
}
#plus {
    margin-left: 24px;
}

JavaScript

var pb,
    $ = function (id) {
        return document.getElementById(id);
    },
    plusBtn = $('plus'),
    minusBtn = $('minus');

function progressBar() {
    var self = this,
        element = $('completed'),
        complete = 0, // percent complete
        color = [240, 40, 40],
        step = 5,
        setBgColor,
        setWidth;
   
   setBgColor = function() {
        element.style.backgroundColor = 'rgb(' +
            color[0] + ', ' +
            color[1] + ', ' +
            color[2] + ')';
    };
    
    setWidth = function () {
        element.style.width = complete + "%";
    };

    this.increase = function () {
        var newTotal = complete + step;
        complete = newTotal > 100 ? 100 : newTotal;

        if (color[1] < 240) {
            color[1] += (4 * step);
        } else if (color[0] > 40) {
            color[0] -= (4 * step);
        }
        setBgColor();
        setWidth();
    };
    
    this.decrease = function () {
        var newTotal = complete - step;
        complete = newTotal < 0 ? 0 : newTotal;

        if (color[0] < 240) {
            color[0] += (4 * step);
        } else if (color[1] > 40) {
            color[1] -= (4 * step);
        }
        setBgColor();
        setWidth();
    };
    
    setBgColor();
}

pb = new progressBar();
plusBtn.onclick = pb.increase;
minusBtn.onclick = pb.decrease;