Return to Snippet

Revision: 64152
at July 10, 2013 01:26 by i-am-andy


Initial Code
HTML:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
</ul>
</code>

jQuery:

$(function(){

  var list = $("ul li").toArray();
  var elemlength = list.length;
  var randomnum = Math.floor(Math.random()*elemlength);
  var randomitem = list[randomnum];
  $(randomitem).css("display", "block");

});

Initial URL
http://forrst.com/posts/Pick_a_random_element_with_jQuery-0hS

Initial Description
A simple way of displaying a random list item. Could be used to randomly display anything.

Demo: jsfiddle.net/uRd6N/ (keep clicking run)

Initial Title
Pick a random element with jQuery

Initial Tags
jquery, text

Initial Language
jQuery