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

Asked

Viewed 1,140 times

-7

I would like a div was alternating colors, two colors preferably. If you want you can put more than one example. But my preference is that the color changes every 40 seconds.

  • 2

    Post what you’ve tried.

  • I haven’t tried it yet, it might be simple a div no body and it changes color 40 second, I haven’t done it since I just got it from how it’s done, but I know it’s possible

  • What you want is something very simple to do, just give a light search. A tip, search for setTimeOut or setInterval. The answer you’ll find yourself.

  • 1

    Thanks guy I’ll take a look

  • 1

    What you want you can do literally in 2 lines of javascript, and you need to use what @Knautiluz indicated. By trying to force you to deepen your knowledge which in itself is quite advantageous

  • @Gersonvaldeir when you get it you can answer your own question, that’s cool because it proves that you tried hard.

Show 1 more comment

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
  • Has the option with JS vanilla?

  • 1

    I’ll update my answer

  • What if I want to use in more than one div? setInterval(Function(){ $('#Divclass'). css('background', Colors[i]); i = (i == (Colors.length -1)) ? 0 : i+1; },5000);

  • Just leave the Divs in the same class

0

Select the div you want to change the color and use a setTimeout function with the number of seconds you need, in the case of 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.