Hi! I want to change background colors using Array. Please help. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Hi! I want to change background colors using Array. Please help.

In the top-right button, I want to add an eventlistener to change multiple background colors using Array. Please suggest how can I do that. ? The for of loop iterates through items of an array. But I have used if condition, I tried adding if inside for(i in colors) { if statement } https://code.sololearn.com/W0BWKeTH0Dgl in function random. Please Help!

16th Apr 2020, 12:26 PM
Priya gupta
Priya gupta - avatar
4 Answers
+ 3
//Confused (:D for sure, that's at least confused) var y = document.getElementById("manycol"); y.addEventListener("click", random); /* function random() { var colors = ["red", "green", "yellow", "gray"] i = 0; for(i in colors){ } if (i = 0, i > colors.length,i++) { document.getElementById("bd").style.backgroundColor = colors[i] } } } */ function random() { var colors = ["red", "green", "yellow", "gray"]; document.getElementById("bd").style.backgroundColor = colors[Math.random()*colors.length|0]; /* x|0 is a short way to get Math.ceil(x) if you want avoid the possibility of having same value twice next, you need a few more logic ;) */ }
16th Apr 2020, 1:00 PM
visph
visph - avatar
0
Thank you.
16th Apr 2020, 6:52 PM
Priya gupta
Priya gupta - avatar
- 1
I want to learn coding??
18th Apr 2020, 8:25 AM
Ní S Hu
Ní S Hu - avatar
- 1
Can u help me??
18th Apr 2020, 8:25 AM
Ní S Hu
Ní S Hu - avatar