johnny
johnny

Reputation: 11

How to change background color multiple times with one button (only JavaScript please)?

I'm kinda new to JavaScript and I'm basically trying to figure out how to have one button that changes the background color on click. At the moment I can do it with three three separate buttons, but I don't know how to do it with just one.

On click I want the next color in my list to be selected.

I have no knowledge on JQuery, so I would appreciate it if the code isn't in JQuery.

This is what I have at the moment:

<button onclick="myFunction1()">Red</button>
<script type="text/javascript">function myFunction1() {
document.body.style.backgroundColor = "red";
}</script>

<button onclick="myFunction2()">Blue</button>
<script type="text/javascript">function myFunction2() {
document.body.style.backgroundColor = "blue";
}</script>

<button onclick="myFunction3()">Green</button>
<script type="text/javascript">function myFunction3() {
document.body.style.backgroundColor = "green";
}</script>

Upvotes: 0

Views: 8820

Answers (3)

Maoz Tamir
Maoz Tamir

Reputation: 26

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <button onclick="changeColor()">click me</button>
    <script>
        var place =0;
        function changeColor() {
            // your color list
            var colorList = ["red","green","blue"];
            // set the color
            document.body.style.backgroundColor = colorList[place]; 
            place++;
            // if place is greater than the list size, reset
            if (place ===colorList.length) place=0; 
        }
    </script>
</body>
</html>

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

var colors = ["red", "blue", "green", "yellow"],   // the color choices
    index = 0;                                     // index of the current color
    
document.getElementById("colorify").onclick = function() {
  document.body.style.background = colors[index];  // set the color of body to the current color
  index = (index + 1) % colors.length;             // increment index to point to the next color (if it goes beyond the length of the coices array get it back to 0 using the modulo %)
}
<button id="colorify">Change color</button>

Upvotes: 2

Przemek
Przemek

Reputation: 3975

const changeColor = document.getElementById('changeColor'),
      colors      = ['red', 'green', 'blue'];
let   colorIndex  = 0;

changeColor.addEventListener('click', () => {
  document.body.style.backgroundColor = colors[colorIndex];      
  colorIndex = (colorIndex + 1) % colors.length
});
<button id="changeColor">changeColor</button>

Upvotes: 3

Related Questions