Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

Gavin Broekema
seal-mask
.a{fill-rule:evenodd;}techdegree
Gavin Broekema
Full Stack JavaScript Techdegree Student 22,443 Points

Adding an alpha value.

var html = '';
var rgbaColor;

function randomRGB () { 
    return Math.floor(Math.random() * 256 );
}

function randomA () {
    return Math.random();
}

function randomColor () {
    var color = 'rgba(';
    color += randomRGB() + ',';
    color += randomRGB() + ',';
    color += randomRGB() + ',';
    color += randomA() + ')';
    return color;
}

function print(message) {
    document.write(message);
}

for ( var i = 0; i < 50; i++) {
    rgbaColor = randomColor();
    html += '<div style="background-color:' + rgbaColor + '"></div>';
}

print(html);

I decided to experiment within my limits by adding an alpha value. Just curious if this was executed correctly.

Is the function randomA() necessary or no?

Gavin Broekema
seal-mask
.a{fill-rule:evenodd;}techdegree
Gavin Broekema
Full Stack JavaScript Techdegree Student 22,443 Points

I'm also curious on how I could go about adding a random background color to the body of my html (to make the alpha value more noticeable). Perhaps document.getElementById() would do the trick? But then how do I change the styles?

1 Answer

Mike Ulvila
Mike Ulvila
16,268 Points

You can set the background color of the body like this.

document.body.style.backgroundColor = "color";