CoderAz
CoderAz

Reputation: 99

Changing background color of div through click event

I have completed studying Javascript codeacademy. I am now in the process of practicing my vanilla JS skills.

I am trying to build a very simple code that changes the background of a div everytime a button is clicked (I realize I can select the div directly by ID but I am using the different selector types and methods so I can get used to them)

document.getElementById("changeColor").addEventListener("click", function() {
  var div = document.getElementById("child").parentNode;
  var random = Math.floor(Math.random() * colors.length);
  var colors = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine"];
  div.style.backgroundColor = colors[random];
})
<div id="example" style="width: 500px; height: 200px; border: solid black 1px; padding: 10px;">
  <p id="child">This is just a quick test</p>

</div>

<button id="changeColor">Change Color</button>

Upvotes: 0

Views: 71

Answers (1)

Dekel
Dekel

Reputation: 62536

Your colors variable is initialized in line #4, and you tried to access it one line before.

You can just switch the two lines and it will work:

document.getElementById("changeColor").addEventListener("click", function(){
   var div = document.getElementById("child").parentNode;
   var colors = ["AliceBlue","AntiqueWhite","Aqua","Aquamarine"];
   var random = Math.floor(Math.random() * colors.length);
   div.style.backgroundColor = colors[random];
})
<div id="example" style="width: 500px; height: 200px; border: solid black 1px; padding: 10px;" >
<p id="child">This is just a quick test</p>

</div>

<button id="changeColor">Change Color</button>

Upvotes: 3

Related Questions