Here, is the simple code where i'm trying to change the background color once I clicked on the button
const colorBtn = document.querySelector('.colorBtn');
const bodyBcg = document.querySelector('body');
const colors = ['red', 'blue', 'yellow', 'green'];
colorBtn.addEventListener('click', changeColor);
// const changeColor = () => {
// let random = Math.floor(Math.random() * colors.length);
// bodyBcg.style.background = colors[random];
// };
function changeColor() {
console.log('color change event');
let random = Math.floor(Math.random() * colors.length);
bodyBcg.style.background = colors[random];
}
body {
display: flex;
min-height: 100vh;
justify-content: center;
align-items: center;
}
.colorBtn {
padding: 0.25rem 0.5rem;
border: 10px;
background-color: gray;
color: white;
outline: none;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hex Colors</title>
<link rel="stylesheet" href="./main.css">
</head>
<body>
<button type="button" class="colorBtn">Click here to change color</button>
<script type="text/javascript" src="./script.js"></script>
</body>
</html>
But when we try with the Arrow Function named changeColor, it's not working: Not able to understand the concept behind this.
const changeColor = () => {
let random = Math.floor(Math.random() * colors.length);
bodyBcg.style.background = colors[random];
};
As well, It works fine in the chrome browser, but when I tried to put debug point on the working changeColor function, It throws error:
const colorBtn = document.querySelector('.colorBtn');
ReferenceError: document is not defined
It is not working because your changeColor
variable is undefined
when you want to link its function to the event listener.
Just define it before attaching your event listener.
const colorBtn = document.querySelector('.colorBtn');
const bodyBcg = document.querySelector('body');
const colors = ['red', 'blue', 'yellow', 'green'];
const changeColor = () => {
let random = Math.floor(Math.random() * colors.length);
bodyBcg.style.background = colors[random];
};
colorBtn.addEventListener('click', changeColor);
body {
display: flex;
min-height: 100vh;
justify-content: center;
align-items: center;
}
.colorBtn {
padding: 0.25rem 0.5rem;
border: 10px;
background-color: gray;
color: white;
outline: none;
cursor: pointer;
}
<button type="button" class="colorBtn">Click here to change color</button>
As a side note: in this case, changeColor
is a variable containing an anonymous function.
Please, look at @Duc Hong's answer for an explanation about hoisting.