Posted By

i-am-andy on 07/10/13


Tagged

random jquery text randomise


Versions (?)

Pick a random element with jQuery


 / Published in: jQuery
 

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

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

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

  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. });

Report this snippet  

You need to login to post a comment.