Exercise : Sometimes Red, Sometimes Blue

Modify redblue.html so that when the button is clicked, it randomly decides whether the background color of the page should be red, or if the background color of the page should be blue. Hint: You can use document.body to access the page's body in JavaScript.

A runnable solution is located here. (Don't peek at the solution code!)

Once you've gotten that working, make your JavaScript code unobtrusive (and way cooler) by taking out the button on the page and choosing a color randomly when the page loads.

Exercise Solution

<button onclick="chooseColor();">RedBlue?!</button>
function chooseColor() {
    var choice = Math.round(Math.random());
    if(choice == 1) {
       document.body.style.backgroundColor = "blue";
    } else {
       document.body.style.backgroundColor = "red";
    }
}