0
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?

2
  • Why is there odd number of " in $(this).css({"background-color": "rgb(1,1,1)});? Commented Nov 12, 2013 at 17:03
  • console.log(color); Commented Nov 12, 2013 at 17:11

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ahh,I think you've cracked it! I am parsing floats into the RGB, as it's a division. Thank you very much. I'll try this now.
Thanks @iambriansreed - I just spotted it as you were changing it :)
0
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.