Ulyssesonline

the tech surfer

  • Home
  • About
  • Archives
You are here: Home / General / JQuery Random Lists

February 18, 2011

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.

<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(){

Filed Under: General Tagged With: jquery, list, random, sort, unordered

Comments

  1. Wholesale pearl jewelry says

    February 25, 2011 at 8:21 pm

    I have a jquery code file.i can send it to you if you.

Copyright © 2003 - 2018