1

I'm trying to change the background color of a particular class one by one with a delay and not everything simultaneously.

.item {
  height: 50px;
  width: 50px;
  background-color: green;
  margin-top: 10px;
}
<div class="item">
</div>

<div class="item">
</div>

<div class="item">
</div>

<div class="item">
</div>
Ganapathy
  • 545
  • 1
  • 6
  • 23
D. Piep
  • 13
  • 5

3 Answers3

4

The comments show solutions with JS. So I will complete this by adding a way to do it in CSS only with animations and delays:

.item {
  height: 50px;
  width: 50px;
  margin-top: 10px;
  background: black;
  animation: colorit 0.5s linear;
  -webkit-animation-fill-mode: forwards;
  -moz-animation-fill-mode: forwards;
  -o-animation-fill-mode: forwards;
  -ms-animation-fill-mode: forwards;
  animation-fill-mode: forwards;
}
.item:nth-child(2) {
  animation-delay: 0.5s;
}
.item:nth-child(3) {
  animation-delay: 1s;
}
.item:nth-child(4) {
  animation-delay: 1.5s;
}
@keyframes colorit {
  from {
    background-color: black;
  }
  to {
    background-color: green;
  }
}
@-webkit-keyframes colorit {
  from {
    background-color: black;
  }
  to {
    background-color: green;
  }
}
<div class="item">
</div>

<div class="item">
</div>

<div class="item">
</div>

<div class="item">
</div>
Marvin
  • 9,164
  • 3
  • 26
  • 44
1

Here is a simple solution by using set timeout with an incrementing value for the timeout

http://codepen.io/Vall3y/pen/woQPeE

$('.item').each(function(i, item) {
  setTimeout(function() {
    item.classList.add('item--colored')
  }, i * 250);
});
Vall3y
  • 1,181
  • 8
  • 18
0

jQuery.fn.extend({
 asyncCss: function(a, b, c) {
     var args = arguments;
          return this.each(function(i) {
            var j = $(this);
            setTimeout(function() {
                j.css.apply(j, args);
            }, i * 1000);

          });
        }
    });

function changeCssAsync() {
  $('.item').asyncCss({
      backgroundColor: 'red',
      width: '10px',
      height: '10px'
  });
}
.item {
  height: 50px;
  width: 50px;
  background-color: green;
  margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item"></div>

<div class="item"></div>

<div class="item"></div>

<div class="item"></div>

<input type="button" onclick="changeCssAsync()" value="Use me as .css() function" />
Laurianti
  • 903
  • 1
  • 5
  • 19