-3

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
Yash Borda
  • 88
  • 7
  • Background color of what? A DOM element? What do the colors in the array mean? – arcyqwerty Aug 12 '22 at 19:50
  • 2
    An *array* is just data, it doesn't have a "background color". What you have is an array of strings. Please clarify what you're trying to do with that array of strings and in what way your attempt does not work as expected. – David Aug 12 '22 at 19:55

2 Answers2

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';
});
1

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)

Crimp
  • 389
  • 1
  • 22