Question

var shadeAmount = 161 / $('.header').length;
        $('.header').each(function (i, e) {
            var shade = i * shadeAmount;
            var color = 'rgb(' + shade + ',' + shade + ',' + shade + ')';
            $(this).css({"background-color": color});
        });

I cannot get the above code to set the background-color property of each header. If I change the code to this:

$(this).css({"background-color": "rgb(1,1,1)"});

It works. So what's wrong with the way I'm declaring color?

Was it helpful?

Solution

Try this...

var count = $(".header").length;
if (count) {
    var shadeAmount = parseInt(161 / count, 10);
    $('.header').each(function (i, e) {
        var shade = i * shadeAmount;
        var color = 'rgb(' + shade + ',' + shade + ',' + shade + ')';
        $(this).css({"background-color": color});
    });
}

I've just sanitised it by wrapping the calculation of shadeAmount in parseInt, to ensure you're not passing floats into the rgb value.

I also added a check that there are elements with the header class, as your code would fail if you ran it on a page where there were none.

OTHER TIPS

var shadeAmount = 161 / $('.header').length;
$('.header').each(function (i, e) {

    var shade = ++i * shadeAmount;

    var color = 'rgb(' + shade + ',' + shade + ',' + shade + ')';

    console.log(color);

    $(this).css({
        "background-color": color
    });
});

fiddle: http://jsfiddle.net/2mUH2/

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