Javascript isnt running well [closed]

I'm following a course where we're building a color game. I followed step by step everything, still my code isn't working at some point.

let colors = [
  "rgb(255, 0, 0)",
  "rgb(255, 255, 0)",
  "rgb(0, 255, 0)",
  "rgb(0, 255, 255)",
  "rgb(0, 0, 255)",
  "rgb(255, 0, 255)"
];

let squares = document.querySelectorAll('.square');

for (let i = 0; i < squares.length; i++) {
  squares[i].style.backgroundColor = colors[i];
}
body {
    background-color: #232323;
}

.square {
    width: 30%;
    background: purple;
    padding-bottom: 30%;
    float: left;
    margin: 1.66%;
}

#container {
    max-width: 600px;
    margin: 0 auto;
}
h1 {
    color: white;
}
<h1>The Great RGB Color Game</h1>

<div id='container'>
  <div class='square'></div>
  <div class='square'></div>
  <div class='square'></div>
  <div class='square'></div>
  <div class='square'></div>
  <div class='square'></div>
</div>

Problem is that my squares aren't changing to the color i passed them in javascript, and i can't figure why, even by inspecting and so on... Anything i missed?

Answers:

Answer

Your square div's dont have a size. Your code works perfectly just give them content or a size with css.

let colors = [
  "rgb(255, 0, 0)",
  "rgb(255, 255, 0)",
  "rgb(0, 255, 0)",
  "rgb(0, 255, 255)",
  "rgb(0, 0, 255)",
  "rgb(255, 0, 255)"
];

let squares = document.querySelectorAll('.square');

for (let i = 0; i < squares.length; i++) {
  squares[i].style.backgroundColor = colors[i];
}
<h1>The Great RGB Color Game</h1>

<div id='container'>
  <div class='square'>1</div>
  <div class='square'>2</div>
  <div class='square'>3</div>
  <div class='square'>4</div>
  <div class='square'>5</div>
  <div class='square'>6</div>
</div>

Answer

You need to specify a size for your squares or fill them with content.

let colors = [
  "rgb(255, 0, 0)",
  "rgb(255, 255, 0)",
  "rgb(0, 255, 0)",
  "rgb(0, 255, 255)",
  "rgb(0, 0, 255)",
  "rgb(255, 0, 255)"
];

let squares = document.querySelectorAll('.square');

for (let i = 0; i < squares.length; i++) {
  squares[i].style.backgroundColor = colors[i];
}
.square { display: inline-block; width: 2em; height: 2em; }
<h1>The Great RGB Color Game</h1>

<div id="container">
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
  <div class="square"></div>
</div>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.