-3

First time poster.

I am trying to change the background colour after clicking a button. I have tried a few different code types and what seems to be consistent is that the array doesn't get iterated properly.

Please Help

var color = ["red", "green", "blue"];
var i = 0;
document.querySelector("button").addEventListener("click", function() {
  i = i < color.length ? ++i : 0;
  document.querySelector("body").style.background = color[i];
})
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

button {
  position: absolute;
  top: 50%;
  left: 50%;
  cursor: pointer;
}

body {
  background-color: blue;
}
<button>Click me to change background colour.</button>
Heretic Monkey
  • 10,498
  • 6
  • 45
  • 102
goosey9
  • 5
  • 2

3 Answers3

1

You should use the modulus when you increment, so that it loops through.

i = (i+1) % color.length;
nbrix
  • 316
  • 1
  • 6
1

So, in Javascript, arrays start from zero, so color[0] is red, color[1] is green and color[2] is blue, when you say color.length it will return 3. so color[3] is undefined because the last color ends at index 2. Also you should start with i= -1 since when you start with 0 and you increment, 0 will become 1 so you skip first color.

var color = ["red", "green", "blue"];
var i = -1;
document.querySelector("button").addEventListener("click", function () {
  i = i < color.length - 1 ? ++i : 0;

  document.querySelector("body").style.background = color[i];
});
Why u do dis
  • 239
  • 9
-3

Be careful to load your javascript script after the button in your HTML code, because otherwise the querySelector will not find it!

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>Background Colour Change</title>
    <link rel="stylesheet" href="new1.css">
</head>
<body>
    <button>Click me to change background colour.</button>
</body> 
<script src="new1.js"></script>

[EDIT] Although this solved your problem, it appears that it is not the safest way to load your script, you need to listen for when the document is ready. I suggest ready about it in this post

alentejo
  • 170
  • 8
  • This fixed it!! Thanks! – goosey9 Apr 05 '21 at 21:04
  • You are welcome. I note that you had the HTML posted in your first post, but then you removed it, so people might get puzzled as to how this solution can be relevant. I suggest to add it back :) – alentejo Apr 05 '21 at 21:12
  • i am sorry but i dont know how to do that – goosey9 Apr 05 '21 at 21:16
  • 1
    The solution is to attach the functionality to document.ready so you can be sure that the DOM is fully available before trying to modify it. That's why your answer has so many downvotes. You're simply increasing the chances of the DOM being ready by loading the script further down the line, but without any definitive guarantee. – Alexander Gräf Apr 05 '21 at 21:30