I was looking for a JQuery code that would display a random order of unordered list. The HTML markup is displayed below. Each time the page is loaded, a different order of list is displayed.
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
Here’s the piece of JQuery code that you’ll need add to your webpage to sort and randomize your unordered list.
<script>$(document).ready(function(){
$(‘ul’).each(function(){
// get current ul
var $ul = $(this);
// get array of list items in current ul
var $liArr = $ul.children(‘li’);
// sort array of list items in current ul randomly
$liArr.sort(function(a,b){
// Get a random number between 0 and 10
var temp = parseInt( Math.random()*10 );
// Get 1 or 0, whether temp is odd or even
var isOddOrEven = temp%2;
// Get +1 or -1, whether temp greater or smaller than 5
var isPosOrNeg = temp>5 ? 1 : -1;
// Return -1, 0, or +1
return( isOddOrEven*isPosOrNeg );
})
// append list items to ul
.appendTo($ul);
});
});</script>
In addition, you can add a class to your unordered list like the example below:
<div class=”sample”>
<ul>
<li>…</li>
<ul>
</div>
You will need to change this line to include the class.
$(‘.sample ul’).each(function(){
I have a jquery code file.i can send it to you if you.