JQuery Random Lists

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.


Here’s the piece of JQuery code that you’ll need add to your webpage to sort and randomize your unordered list.

// 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
// 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

In addition, you can add a class to your unordered list like the example below:

<div class=”sample”>

You will need to change this line to include the class.

$(‘.sample ul’).each(function(){

1 thought on “JQuery Random Lists

Comments are closed.