-3

Here's my JS code. Console is showing

randomColor is not defined

var colors = ["#81ecec", "#0984e3", "#fab1a0", "#81ecec", "#0984e3", "#fab1a0"];

let button = document.querySelector("#button");

button.addEventListener("click", function() {
   var changeColor = colors[Math.floor(Math.random() * colors.length)];
});

let content = document.querySelector("#container").style.background = changeColor;
James Z
  • 12,209
  • 10
  • 24
  • 44
  • 2
    Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Sebastian Simon Aug 04 '20 at 11:54
  • Did you edit your code to have "changeColor" instead of "randomColor", because now you have an error that doesn't match your code. – James Z Aug 04 '20 at 13:13
  • I simply, shifted the Last Line of the Code (style.background) inside the function. – theCoderRaj Aug 06 '20 at 08:26

1 Answers1

0

changeColor is only inside the click function readable because of the scope, so you had to change the color as well there.
Even if you would declare it globally this wouldn't help you: There wouldn't be than be though any errors but the background color change would be executed only once at script start but than changeColor is null and so anything would happen.

var colors = ["#81ecec", "#0984e3", "#fab1a0", "#81ecec", "#0984e3", "#fab1a0"];
let button = document.querySelector("#button");

button.addEventListener("click", function() { 
    let changeColor = colors[Math.floor(Math.random() * colors.length)]; 
    let content = document.querySelector("#container").style.background = changeColor;
});
<div id='container'>
  <button id='button'>btn</button>
</div>
Sascha
  • 4,576
  • 3
  • 13
  • 34