skip to Main Content

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


  1. 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

    function blinkBG(){
             blink = badBG()
             var elems = document.getElementsByClassName('Bad'),
             size = elems.length;      
             for (var i = 0; i < size; i++) {
                    var box = elems[i];
                    box.style.backgroundColor = blink;
             }
        }
    
    Login or Signup to reply.
  2. Better use a CSS animation:

    .bad{
      padding:30px;
      animation: blink 300ms infinite;
    }
    
    @keyframes blink{
      from {
        background: white;
      }
      to{
        background: red;
      }
    }
    <div class="bad">I'm very bad</div>
    Login or Signup to reply.
  3. 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 with classList.toggle() to toggle a class in CSS. Means by adding/removing it:

    const BAD = document.querySelectorAll('.bad');
    
    BAD.forEach(element => {
      setInterval(function() {
        element.classList.toggle('bg-red');
      }, 300)
    })
    .bad{
      padding:30px;
    }
    
    .bg-red {
      background-color: red;
    }
    <div class="bad">I'm very bad</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search