I am trying to have a blinking background color between Red and Wite by writing 2 functions with 3milli-seconds interval, but unfortunately, it doesnt work with my set element class named, "Bad".
Can someone help me what am I doing wrong?
Code is below:
function badBG(){
var colors = ['Red','White']
for(i=0; i<2; i++){
colorBG = colors[Math.floor(Math.random()*2)];
// console.log(colorBG)
}
return colorBG
}
function blinkBG(){
blink = badBG()
document.getElementsByClassName('Bad').style.backgroundColor = blink;
}
setInterval("blinkBG()",300);
All are straight to the point functions and css methods.
3
Answers
The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s). So you should try like this
Better use a CSS animation:
While I would recommend solely solving this on the CSS level as Alexander Nenashev showed, there is also a clean JavaScript solution to it.
You simply us
setInterval
in combination withclassList.toggle()
to toggle a class in CSS. Means by adding/removing it: