Search code examples
javascripthtmlcssfunctiontags

Blinking Background color in JavaScript


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.


Solution

  • Better use a CSS animation:

    .bad{
      padding:30px;
      animation: blink 300ms infinite;
    }
    
    @keyframes blink{
      0%, 49.9% {
        background: white;
      }
      50%, 99.9% {
        background: red;
      }
    }
    <div class="bad">I'm very bad</div>