skip to Main Content

how to change background color in array with javascript.

let back_color = [‘#FFEEDE’, ‘#EAFFE2’, ‘#FFEEDE’, ‘#EAFFE2’, ‘#FFEEDE’, ‘#EAFFE2’, ‘#FFEEDE’, ‘#EAFFE2’, ‘#FFEEDE’, ‘#EAFFE2’];

let i = 0;

$("#prev").click(function () {

 i = i < back_color.length ? --i : 0;

 $('.back-color').css("background", "" + back_color[i] + "" );

});

$("#next").click(function () {

 i = i < back_color.length ? ++i : 0;

 $('.back-color').css("background", "" + back_color[i] + ""  );

});

html ==>

change color

2

Answers


  1. Below code will change the value of element in array –

    back_color.forEach((element, index) => {
      back_color[index] = 'your new value should go here';
    });
    
    Login or Signup to reply.
  2. Is this what you’re looking for?

    const back_color = ['#FFEEDE', '#EAFFE2', '#FFEEDE', '#EAFFE2', '#FFEEDE', '#EAFFE2', '#FFEEDE', '#EAFFE2', '#FFEEDE', '#EAFFE2'];
    
    function backColor(){
      const random = Math.floor(Math.random() * back_color.length);
      document.body.style.backgroundColor = back_color[random];
    }
    <button onclick="backColor()">Change background color</button>

    Sources (Getting a random value from a JavaScript array) & (https://bobbyhadz.com/blog/javascript-change-background-color-on-click)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search