kanarek58
kanarek58

Reputation: 53

My loop for changing background-color doesn't work

I'd like to make a loop that every 8 seconds change my div ("items") background-color to white for 1s, and then back to black.

let x;

function changeColor() {
  x = setInterval(xyz, 1000);
}

function xyz() {
  let elem = document.getElementsByClassName("items");
  if (elem[0].style.backgroundColor == 'black') {
    elem[0].style.backgroundColor = 'white';
  } else {
    elem[0].style.backgroundColor = 'black';
  }
}

function stopchangeColor() {
  clearInterval(x);
}
<div class="items" style="background-color: black;"></div>

Upvotes: 1

Views: 315

Answers (3)

greeed
greeed

Reputation: 64

it seems to work...

const elem = document.getElementsByClassName("items");

function xyz() {
  elem[0].style.backgroundColor = '#ffffff'
  setTimeout(() => {
    elem[0].style.backgroundColor = '#000000'
  }, 1000)
}
setInterval(() => xyz(), 8000);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .items {
      background-color: black;
      min-width: 100%;
      min-height: 500px;
    }
  </style>
</head>

<body>

  <div class="items">
  </div>
</body>

</html>

Upvotes: 0

Oppo_Oskar
Oppo_Oskar

Reputation: 41

In your example the div was empty and no size set so nothing was showing.

You also need to start the timer as well as set a different timer depending on if it's black or white :)

let x;

function xyz() {
  let elem = document.getElementsByClassName("items");
  if (elem[0].style.backgroundColor == 'black') {
    elem[0].style.backgroundColor = 'white';
    clearInterval(x);
    x = setInterval(xyz, 1000);
  } else {
    elem[0].style.backgroundColor = 'black';
    clearInterval(x);
    x = setInterval(xyz, 8000);
  }
}

function stopchangeColor() {
  clearInterval(x);
}

x = setInterval(xyz, 8000);
.items {
  width: 100%;
  height: 50px;
}
<div class="items" style="background-color: black;"></div>

Upvotes: 1

Pranav Rustagi
Pranav Rustagi

Reputation: 2721

Explanation : the function changeColor() sets setInterval to call function xyz() once in every 8 seconds. Then, in function xyz(), the background color is changed to white. The setTimeout changes the background color to black just after one second.

var x;

function changeColor() {
  x = setInterval(xyz, 8000);
}

function xyz() {
  let elem = document.getElementsByClassName("items");
  elem[0].style.backgroundColor = 'white';
  setTimeout(()=>{
    elem[0].style.backgroundColor = 'black';
  }, 1000);
}

function stopchangeColor() {
  clearInterval(x);
}


changeColor();
.items {
  width: 400px;
  height: 200px;
}
<div class="items" style="background-color: black;"></div>

Upvotes: 2

Related Questions