Supergogoman91 Supergogoman91 - 29 days ago 11
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!

https://jsfiddle.net/8dL3zvcp/

HTML:

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


Jscript:

$("document").ready(function(){



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

});

Answer

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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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);
}
setBackground();
setInterval(setBackground, 2000);
<div class="one toggle-a">This is the div</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments