Pick a random element with jQuery


/ Published in: jQuery
Save to your folder(s)

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

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


Copy this code and paste it in your HTML
  1. HTML:
  2.  
  3. <ul>
  4. <li>Item 1</li>
  5. <li>Item 2</li>
  6. <li>Item 3</li>
  7. <li>Item 4</li>
  8. <li>Item 5</li>
  9. <li>Item 6</li>
  10. </ul>
  11. </code>
  12.  
  13. jQuery:
  14.  
  15. $(function(){
  16.  
  17. var list = $("ul li").toArray();
  18. var elemlength = list.length;
  19. var randomnum = Math.floor(Math.random()*elemlength);
  20. var randomitem = list[randomnum];
  21. $(randomitem).css("display", "block");
  22.  
  23. });

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.