nabisu
nabisu

Reputation: 11

using forEach() to change background color after clicking a button

I want to change a color everytime I click a button. I use forEach to go through each color. But after I click a button, the color changes to "orange", the last color in the array. Am I missing something in my code?

window.onload = function() {
    const btn = document.querySelector("button");
    btn.addEventListener("click", changeColor); 
}

function changeColor() {
    const colors = ["yellow","green","red","blue","orange"];
    colors.forEach(function(color) {
        document.body.style.backgroundColor = color;
    });
}
body{
    background-color:teal;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 180px;
}

button{
    background-color: white;
    font-size: 30px;
    width: 150px;
    height: 50px;
    border-style: solid;
    border-color: black;
    border-radius: 10px;
    cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/style.css">
    <script src="/js.js"></script>
    <title>1st project</title>
</head>
<body>
    <button class="button">Click me!</button>
    
</body>
</html>

Upvotes: 1

Views: 1589

Answers (4)

Yahya Altintop
Yahya Altintop

Reputation: 224

If you want change color in order, this is a simple method

let index = 0;

window.onload = function() {
    const btn = document.querySelector("button");
    btn.addEventListener("click", changeColor);
}

function changeColor() {
    const colors = ["yellow", "green", "red", "blue", "orange"];

    (index != colors.length - 1) ? index++ : index = 0; // Reset if index equals color array length

    document.body.style.backgroundColor = colors[index]
}

Upvotes: 0

Sanmeet
Sanmeet

Reputation: 1410

If you want to change the background complete random then use Math.random() method ( I made it little advanced to set max and min values )

RANDOM ( change to random background color )

       window.onload = function() {
      const btn = document.querySelector("button");
      btn.addEventListener("click", changeColor);
    }
    Math.randomNumber = (min, max)=> {
      return Math.round(Math.random() * (max - min) + min);
    };
    
    function changeColor() {
      const colors = ["yellow",
        "green",
        "red",
        "blue",
        "orange"];

      // Getting a random num b/w 0 and  colours array length 
      const num = Math.randomNumber(0, colors.length)
     // Chaining the colours 
      document.body.style.backgroundColor = colors[num];
    }
 

LOOPING ( if you want to loop in array of colours )

     window.onload = function() {
      const btn = document.querySelector("button");
      btn.addEventListener("click", changeColor);
    }
    // set Default color by changing the value 
    let currentNum = 0;
    function changeColor() {
      const colors = ["yellow",
        "green",
        "red",
        "blue",
        "orange"];
      
      if(currentNum >= colors.length - 1){
         currentNum = 0;
      }else{
        currentNum++
      }
      document.body.style.backgroundColor = colors[currentNum];
    }

Upvotes: 0

pistou
pistou

Reputation: 2867

You'd have to somehow save the current color then change to the next one. For this, you could put the current index of the colors array in a variable:

window.onload = function() {
    const btn = document.querySelector("button");
    btn.addEventListener("click", changeColor); 
}

let colorIndex = 0;
const colors = ["teal", "yellow","green","red","blue","orange"];

function changeColor() {
    colorIndex++;
    if ( colorIndex >= colors.length) {
        colorIndex = 0; // Circle back to the start
    }
    document.body.style.backgroundColor = colors[colorIndex];
}
body{
    background-color:teal;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 180px;
}

button{
    background-color: white;
    font-size: 30px;
    width: 150px;
    height: 50px;
    border-style: solid;
    border-color: black;
    border-radius: 10px;
    cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/style.css">
    <script src="/js.js"></script>
    <title>1st project</title>
</head>
<body>
    <button class="button">Click me!</button>
    
</body>
</html>

Upvotes: 0

pilchard
pilchard

Reputation: 12919

On each click you are iterating over your colors array and setting the background to each color in the array in succession ending in orange.

Instead you need to track the index of the last click and increment it on each click, here using the remainder operator(%) to loop back to 0.

let colorIndex=0;
function changeColor() {
    const colors = ["yellow","green","red","blue","orange"];
    document.body.style.backgroundColor = colors[colorIndex];
    colorIndex = (colorIndex+1)%colors.length;
}

window.onload = function() {
    const btn = document.querySelector("button");
    btn.addEventListener("click", changeColor); 
}

let colorIndex=0;
function changeColor() {
    const colors = ["yellow","green","red","blue","orange"];
    document.body.style.backgroundColor = colors[colorIndex];
    colorIndex = (colorIndex+1)%colors.length;
}
body{
    background-color:teal;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 180px;
}

button{
    background-color: white;
    font-size: 30px;
    width: 150px;
    height: 50px;
    border-style: solid;
    border-color: black;
    border-radius: 10px;
    cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/style.css">
    <script src="/js.js"></script>
    <title>1st project</title>
</head>
<body>
    <button class="button">Click me!</button>
    
</body>
</html>

Upvotes: 2

Related Questions