-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.
-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.
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?
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 javascript html div
You are not signed in. Login or sign up in order to post.
Post what you’ve tried.
– Jefferson Quesado
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
– Gerson Valdeir
What you want is something very simple to do, just give a light search. A tip, search for
setTimeOut
orsetInterval
. The answer you’ll find yourself.– Raizant
Thanks guy I’ll take a look
– Gerson Valdeir
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
– Isac
@Gersonvaldeir when you get it you can answer your own question, that’s cool because it proves that you tried hard.
– Raizant