samedi 23 février 2019

jQuery: display several elements randomly with different timings

I'm trying to randomly display divs on different positions, but I can only display them at the same time and the goal is to have diferent, dinamic timings for each div: the first div changes position one second after the other, for example. I've researched but similar solutions didn't apply and I'm failing to use the each() function? Can someone give a help?

HTML:

<div class="container">           
        <div class="wound"></div>
        <div id="first-row">
            <div class="box"></div>
            <div class="box" id="red">                  
            </div>
            <div class="box"></div>
            <div class="box"></div>
            <div class="box" id="blue">
            ></div>
            <div class="box"></div>
        </div>
        <div id="second-row">
            <div class="box"></div>
            <div class="box"></div>
            <div class="box">                   
            </div>
            <div class="box"></div>
            <div class="box">
            </div>
            <div class="box"></div>
        </div>
    </div>

JS

    var firstRow = $('#first-row');
    var secondRow = $('#second-row');

    function randomize(target, row) {
        while (target.length) {
            row.append(target.splice(Math.floor(Math.random() * target.length), 1)[0]);
        }
    }


    function randomMove(parent, secondParent) {
        parent = firstRow;
        secondParent = secondRow;
        var secondBandit = secondParent.children();
        var bandit = parent.children();
        randomize(bandit, firstRow)
        randomize(secondBandit, secondParent);
    }

    var seconds = 4000;
    function timer(seconds) {
        seconds = seconds;
        setInterval(function () {

            randomMove();
            playerShot();
        }, seconds);
    }
    timer(seconds);

Here is the fiddle




Aucun commentaire:

Enregistrer un commentaire