Dima Vleskov Dima Vleskov - 1 year ago 97
Javascript Question

how to change color of elements one by one using javascript(jquery) and then reset the result again one by one

how to change color of elements one by one using javascript(jquery) and then reset the result again one by one

.cub {
background: aqua;
width: 200px;
height: 200px;
display: inline-block;
}








Answer Source

Please try this code if it works. I was not able to check it but it should work.

<div class="cub"></div>
<div class="cub"></div>
<div class="cub"></div>
<div class="cub"></div>

.cub{ background-color: white; }
.cub.highlighted{ background-color: aqua; }

    <script>
      var highlighting = true;

      $(document).ready(function(){
        var highlightingInterval = setInterval(function(){
          if( $(".cub.highlighted").length == 0 )
            highlighting = true;
          else if( $(".cub.highlighted").length == 4 )
            highlighting = false;

          if( highlighting )
          {
            $(".cub").not(".highlighted").eq(0).addClass("highlighted");
          }
          else
          {
            var targetIndex = $(".cub.highlighted").length - 1;                                  $(".cub.highlighted").eq(targetIndex).removeClass("highlighted");
          }
        }, 2000 );//setInterval
      });//document ready
    </script>