How to change the color of a div every 40 seconds?

-7

I would like a% color to be alternating colors, preferably two colors. If you want you can put more than one example. But my preference is for the color to change every 40 seconds.

    
asked by anonymous 15.10.2017 / 18:11

2 answers

1

You can do this with jQuery simply, as follows:

$(document).ready(function() {
    var colors = ["#f9f9f9", "#049fce"];//Array com as cores, pode adicionar contas quiser
    var i = 0;
    setInterval(function(){
      $('.divclass').css('background', colors[i]);
      i = (i == (colors.length -1)) ? 0 : i+1;
    },40000);//40 Segundos em Milisegundos
});

Or with pure JavaScript:

var colors = ["#049fce", "#f9f9f9"];//Array com as cores, pode adicionar contas quiser
var i = 0;
setInterval(function(){
  document.getElementById('divid').style.background = colors[i];//A div deve ter um id, não funciona com class
  i = (i == (colors.length -1)) ? 0 : i+1;
},40000);//40 Segundos em Milisegundos
    
15.10.2017 / 20:26
0

Select the div you want to change the color and use a setTimeout function with the number of seconds you need, in this case, 40000, use an if to make a counter always be the two indexes of an array with two colors, see:

const colorDiv = document.querySelector('.change-color');
let counter = 0;

const colorArr = ['red', 'yellow']

setInterval(
	()=> {
		counter++
		
		if (counter == colorArr.length) {
			counter = 0
		}
		
		colorDiv.style.background = colorArr[counter];
	}, 3000
)
.change-color {
	background: red;
	width: 300px;
	height: 300px;
}
<div class="change-color"></div>
    
15.10.2017 / 21:26