blazerix blazerix - 1 year ago 74
CSS Question

Javascript transitions not executing in order

I have a circle, consisting of 12 arc segments and I want to allow the user to see the transition from the start pattern to the end pattern. (there will be many start and end patterns).

Here is my code so far:

function playAnimations(){
var totalLength = document.getElementsByClassName("container")[0].children.length

for(var i = 0; i < totalLength; i++){
var current_pattern = document.getElementsByClassName("container")[0].children[i]
for(var j = 0; j < 12; j++){
$('#LED' + (j+1) ).css('transition-duration', '0s');
$('#LED' + (j+1) ).css({fill: current_pattern.children[1].children[j].style.backgroundColor});


setTimeout(function () {
for(var k = 0; k < 12; k++){
$('#LED' + (k+1) ).css('transition-duration', "" + current_pattern.children[3].children[0].value + "ms");
$('#LED' + (k+1) ).css({fill: current_pattern.children[2].children[k].style.backgroundColor});

}, 150);


The outer for loop goes through all of the patterns, and the two inner for loops will go through the start and end pattern respectively. For some reason, my program only displays the animation of the very last pattern. I suspect this is because the code is executing really quickly - however I am unsure of how to fix this.

Does anyone know a good workaround or what I could possibly do to rectify this issue? Any feedback or help is appreciated.

Answer Source

Ok, not entirely understanding all the parts of your code, I've whipped this up. It doesn't work just yet, but you may get the idea of what I'm trying to do: wait 250 milliseconds before you fire off the next animation, once you run out of siblings, bounce to the other animation. I can't spend any more time on this, but I hope this gets you where you want to be:

function playAnimations() {
    var patternHolder = $(".container")[0];
    playAnimation($('#LED1'), 0, patternHolder, 1, 1);

function playAnimation($target, index, patternHolder, childPatternIndex, animationNumber) {

    //just set both fill color and transition in the object you pass in:
    //.eq() chooses a child, returns jQuery object of that child by index
    //Use jQuery to get background-color style
    $target.css({ fill: $(patternHolder).children(childPatternIndex).children().eq(index).css("background-color"), transition: "0s" });

    setTimeout(function () {
        if ($target.parent().next().length > 0) {
            playAnimation($target.parent().next(), index++);
        } else if (animationNumber == 1) {
            playAnimation($("#LED1"), 0, patternHolder, 3, 2);
    }, 250);  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download