0

I am trying to change the background color when the button is clicked. But instead of the color being changed sequentially when I click the button, it directly changes to the last one. How do I fix it by using for loop only.

but.addEventListener("click", clickfunction);

function clickfunction() {
  color = arr.shift();
  arr.push(color);
  bgcolor.style.background = color;
  but.style.color = color;
  but.innerText = color;
  comming[0].style.background = --color;
};
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • I made you a snippet. Click edit, then scroll down and "edit above snippet" - paste relevant Script HTML and CSS to provide a [mcve] - we need your elements and your color array – mplungjan Jan 03 '21 at 12:58
  • You need a setTimeout to allow the DOM to change. Now your loop is too fast for the DOM. Also I assume you want to change the backgroundColor – mplungjan Jan 03 '21 at 12:59
  • Also please [look for dupes](https://www.google.com/search?q=javascript+change+background+color+loop) before asking – mplungjan Jan 03 '21 at 13:01
  • Could you tell us what is stored in **color** variable? Because last line with **--color;** looks very suspicious – Abbas Akhundov Jan 03 '21 at 13:02
  • Answer : https://jsfiddle.net/donqq/f2bda7jp/23/ – Don Dilanga Jan 03 '21 at 13:09

0 Answers0