I will usually search on Google first, but I searched and did not find a valid solution.
I'm doing a guessing game of Coursera's Javascript course colors.
And it is working but when I try to set backgroundColor
of <body>
I get the following error:
"Uncaught TypeError: Can not read property 'style' of null"
Does any of you have any idea how to solve this?
Code
do_game();
function do_game() {
//lower or higher
// =-=-=-=- Get array of colors
var colors = getColors();
// =-=-=-=- Get Randomize number based on the number of colors
var colorId = getRandomNumber(colors.length - 1);
// =-=-=-=- Show Answer to the Tester
alert(getAnswer(colors[colorId]));
// Loop until find the answer
var userColorId = 0;
var times = 0;
while (colorId != userColorId) {
times++;
//get userColorID
var userColor = prompt(getQuestion());
userColorId = getColorId(colors, userColor);
// Color not in the Array
if (userColorId === -1) {
alert(getNotListCollorError());
}
//Color
//alert(colorId + ">" + userColorId);
if (colorId > userColorId) {
alert(getListCollorError('lower'));
} else if (colorId < userColorId) {
alert(getListCollorError('higher'));
} else if (colorId == userColorId) {
var color = colors[userColorId];
alert(color);
setBackgroundColor(color);
console.log(color);
//alert(getSucessMessage(times));
}
}
}
function getColorId(array, color) {
return array.indexOf(color);
}
function setBackgroundColor(name_of_color) {
myBody = document.getElementsByTagName("body")[0];
myBody.style.backgroundColor = color;
document.body.style.backgroundColor = name_of_color;
}
function getColors() {
var colors = ['blue', 'cyan', 'gold', 'green', 'magenta', 'orange', 'red', 'white', 'yellow'];
return colors;
}
function getQuestion() {
var txtQuestion = 'I am thinking of one of these colors:' + '\n\n' + getColors() + '\n\n' + 'What color am I thinking of?';
return txtQuestion;
}
function getListCollorError(position) {
var txtMensage = "Sorry your guess is not correct!" + '\n\n' + "Hint: your color is alphabetically " + position + " than mine." + '\n\n' + "Please try again.";
return txtMensage;
}
function getNotListCollorError() {
var txtMensage = "Sorry, I dont recognize your color." + "\n\n" + "Please try again.";
return txtMensage;
}
function getSucessMessage(times) {
var txttimes = (times > 1) ? 'guesses' : 'guess';
var txtMensage = "Congratulations! You have guessed the color!" + "\n\n" + "It took you " + times + " " + txttimes + "\n\n" + "You can see the color in the background";
return txtMensage;
}
function getAnswer(answer) {
return "The answer is: " + answer;
}
function getRandomNumber(maxnumber) {
return Math.round(Math.random() * maxnumber);
}
<style>
background{
background-color: aqua;
}
</style>
<script src="game.js">
</script>
<body>
<h1>
Color Guessing Game
</h1>
</body>