I tried this project from a little while ago and even copy and pasted some parts from the working projects I had saved. The background color wont change and I am confused.
const colors = ['red', 'green', 'blue'];
const colorIndex = -1;
let myFunction = () => {
colorIndex += 1;
if (colorIndex > colors.length-1) colorIndex = 0;
document.body.style.backgroundColor = colors[colorIndex];
}
body{
text-align: center;
}
#btn {
margin-top: 25%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Colour Flipper</title>
<link rel="stylesheet" href="color.css">
</head>
<body>
<button id="btn" onclick="myFunction()">Click to change colour</button>
</body>
<script src="color.js"></script>
</html>
Uncaught TypeError: Assignment to constant variable. Change constant variable
const colorIndex = -1;
to
let colorIndex = -1;
Use let instead of const. You cannot reassign const.
const colors = ['red', 'green', 'blue'];
let colorIndex = -1;
let myFunction = () => {
colorIndex += 1;
if (colorIndex > colors.length-1) colorIndex = 0;
document.body.style.backgroundColor = colors[colorIndex];
}
This is the Javascript. You initialise the variables with const. But you have to do it with let or var.
let colors = ['red', 'green', 'blue'];
let colorIndex = -1;
let myFunction = () => {
colorIndex += 1;
if (colorIndex > colors.length-1) colorIndex = 0;
document.body.style.backgroundColor = colors[colorIndex];
}