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.