简体   繁体   中英

How can I randomize elements selected in a JQuery each loop

I have been working on this functionality where I have 5 circles then when a button is clicked they all move down the page one at a time in order. I am trying to get them to go down in a random order. (if not random at least something that doesn't make them fall in order)

JsFiddle: https://jsfiddle.net/n12zj90p/2/

HTML:

<div class="container">

    <button>CLICK</button>

    <div class="circle circle-1"></div>
    <div class="circle circle-2"></div>
    <div class="circle circle-3"></div>
    <div class="circle circle-4"></div>
    <div class="circle circle-5"></div>

</div>

CSS:

.circle{
    width: 40px;
    height: 40px;
    position: absolute;
    background: red;
    border-radius: 100%;
}

.circle-1{ top: 10em; left: 10em; }

.circle-2{ top: 20em; left: 20em; }

.circle-3{ top: 30em; left: 30em; }

.circle-4{ top: 40em; left: 40em; }

.circle-5{ top: 50em; left: 50em; }

button{ padding: 10px 50px; display: table; margin: auto; }

JQUERY:

$(document).ready(function(){
    var $c = $(".circle");

    $("button").click(function(){

        $c.each(function(i, elem){
            $(elem).delay(i * 500).animate({top:"300em"}, { duration: 2000, complete: function(){
                //just something to do after the animation has been completed, you can disregaurd this area
                }
            });//animate end            
        });//each end          

    });
});

var $c = $(".circle"); is an array. So you just need to randomly shuffle it before doing each on it

function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

shuffle($c).each(...

Shuffle comes from here

Not sure I deserve any credit for this because it was Pointy's idea, but here's a code that's working and pretty simple:

$(document).ready(function(){
    var $c = $(".circle");

    $("button").click(function(){

        $c.each(function(i, elem){
            var rando_time = Math.floor((Math.random() * 600) + 1);
            $(elem).delay(i * rando_time).animate({top:"300em"}, { duration: 2000, complete: function(){
            //just something to do after the animation has been completed, you can disregaurd this area
            }
            });//animate end            
        });//each end 

    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM