Skip to content Skip to sidebar Skip to footer

Change Div Background Color, Depending On Its Width

I'm wanting to use jQuery to dynamically modify the background color of a
, based on its CSS property, width value. The usage is for some form of color-coded meter, whic

Solution 1:

I'd suggest:

$('.rating-bar').css('background-color', function(){
    var percentage = parseInt($(this).data('size'), 10);
    if (percentage > 0 && percentage < 25){
        return'#a41818'
    }
    elseif (percentage > 24 && percentage < 50) {
        return'#87581c';
    }
    elseif (percentage > 49 && percentage < 75) {
        return'#997815';
    }
    elseif (percentage > 74 && percentage < 90) {
        return'#7ba01c';
    }
    elseif (percentage > 89 && percentage <= 100) {
        return'#3a8d24';
    }    
});

JS Fiddle demo.

Solution 2:

There were a few semantic problems ($(e) used instead of $(this), ($(document).ready nested strangely), and the logic you've used requires the ratio of each bar's width to the parent bar, not the width itself.

Try this: http://jsfiddle.net/VFSUN/1/

$(document).ready(function () {
    var bar = $('.rating-bar');
    bar.css("background-color", "#7ba01c");

    var parentWidth = parseInt($('.rating-bar-bg').css("width"));
    $('.rating-bar').each(function () {
        var e = $(this).css("width");
        e = parseInt(e);
        ratio = e / parentWidth * 100;
        if (ratio <= 24) {
            $(this).css("background-color", "#a41818");
        } elseif (ratio >= 25 && e < 50) {
            $(this).css("background-color", "#87581c");
        } elseif (ratio >= 50 && e < 75) {
            $(this).css("background-color", "#997815");
        } elseif (e >= 75 && e < 91) {
            $(this).css("background-color", "#7ba01c");
        } elseif (ratio >= 91) {
            $(this).css("background-color", "#3a8d24");
        }
    });
});

Solution 3:

I suggest you are starting at wrong point by checking width, when in fact you need to be setting width based on the data-size attribute. This size can then be used to set bckground color

$(document).ready(function() {
  $('.rating-bar').each(function(){
        var $bar=$(this), size=$bar.data('size');
        $bar.width(size+'%').css("background-color", getBackground( size))
    });       
});    


 functiongetBackground( e){
    var  color= "#a41818";/* < 24*/if (e >= 25 && e < 50) {
             color= "#87581c";
        } elseif (e >= 50 && e < 75) {
            color=  "#997815";
        } elseif (e >= 75 && e < 91) {
            color=  "#7ba01c";
        } elseif (e >= 91) {
            color=  "#3a8d24";
        }    
    return color

}

DEMO

Post a Comment for "Change Div Background Color, Depending On Its Width"