Supergogoman91 Supergogoman91 - 1 year ago 72
Javascript Question

Is it possible to animate using loops (for/while)

I may be barking up the wrong tree completely, but I'm looking for a way to animate an element on a page persistently on load. I've played around a bit using for loops but can't get it to work, and while loops are of course just infinite. Below is a fiddle of what I'm aiming for, any help would be appreciated!


<div class="one"></div>



for (i = 0; i < 10; i++) {
$(".one").css("background-color", "red").delay(2000).css("background-color" ,"blue").delay(2000);


Answer Source

I'd use a pair of classes and toggle them once per desired interval repeatedly:

setInterval(function() {
  $(".one").toggleClass("toggle-a toggle-b");
}, 2000);
.toggle-a {
  background-color: blue;
.toggle-b {
  background-color: green;
<div class="one toggle-a">This is the div</div>
<script src=""></script>

But if you really want to do it with inline styles, track which one you're currently showing and again toggle:

var current = "";
function setBackground() {
  current = current === "blue" ? "green" : "blue";
  $(".one").css("background-color", current);
setInterval(setBackground, 2000);
<div class="one toggle-a">This is the div</div>
<script src=""></script>