jQuery: show random
June 19, 2013 11:02 am
Leave your thoughts
Here’s a little jquery snippet that shows at random an <li> within a <ul>
<script type="text/javascript"> $(function(){ $('#randomize li').each(function(){ $(this).hide(); }); var min = 0; var max = $('#randomize li').length; var randomLi = Math.floor(Math.random() * (max - min)) + min; $('#randomize li').eq(randomLi).show(); }); </script> <h3>Randomize this list</h3> <ul id="randomize"> <li> Hello World! </li> <li> Lorem Ipsum </li> <li> Dolor Sit Amet </li> <li> Something else </li> </ul>
A little explanation is in order…
//this section selects all the li within the ul with an id of “randomize” and hides each of them.
$('#randomize li').each(function(){ $(this).hide(); });
//Declare some variables so we have a range to select randomly from
//.length in jquery returns the number of items, in this case 4
//the forumla for randomLi selects a number from our given range (0-4)
var min = 0; var max = $('#randomize li').length; var randomLi = Math.floor(Math.random() * (max - min + 1)) + min;
//.eq in jquery selects an element based on it’s index
//if var randomLi = 1 then it will show the first list item
//if var randomLi = 2 then it will show the second list item
//if var randomLi = 3 then it will show the third list item
//if var randomLi = 4 then it will show the last list item
$('#randomize li').eq(randomLi).show();Tags: .eq, .hide, .length, .show, jQuery, random li, show random li, show random li with jquery
Categorised in: jQuery
This post was written by admin