Reordering a div using jquery

I work on an HTML-based client site and must arbitrarily arrange my set of Divs when I refresh the page. I would usually handle this through PHP and a database call, but this is a static site.

So I'm wondering if anyone knows how to randomly display a set of divs using jquery?

Here is an example:

<div class="myItems"> <div class="item">1</div> <div class="item">2</div> <div class="item">3</div> </div> 

and when updating it can change to:

 <div class="myItems"> <div class="item">2</div> <div class="item">3</div> <div class="item">1</div> </div> 

Does anyone know how to do this?

+4
source share
3 answers

This is actually pretty simple:

 $(".myItems").html($(".myItems .item").sort(function(){ return Math.random()-0.5; })); 

What is it! Enjoy it.

+1
source

It will do it

  function reorder() { var grp = $(".myItems").children(); var cnt = grp.length; var temp,x; for (var i = 0; i < cnt; i++) { temp = grp[i]; x = Math.floor(Math.random() * cnt); grp[i] = grp[x]; grp[x] = temp; } $(grp).remove(); $(".myItems").append($(grp)); } 
+8
source

Another simple way is ... 1. create an array 2. generate a random number and check if it is even or even 3. If odd, add your div to the top (shift method). Even if, add your div to the bottom (push method). 4. This way you will have your divs randomly ordered in an array. 5. Now just connect the array and add it to your page.

 var divArray = []; for(var i=0; i<divs.length; i++){ //generate random number if(rand_num == odd) divArray.push( div[i] ); else divArray.shift( div[i] ); } $(myElem).html( divArray.join("") ); 
0
source

Source: https://habr.com/ru/post/1313212/


All Articles