Select 5 random elements
Solution 1:
Here's how to get 5 random elements from a jQuery selection, no need of plugins!
randomElements = jQuery("li").get().sort(function(){
return Math.round(Math.random())-0.5
}).slice(0,5)
At this point you have 5 DomElements that have been selected randomly from all the LIs that jQuery returned
You can then do whatever you like with them,
e.g change their color:
$(randomElements).css("color","red")
or display their combined text contents:
$(randomElements).text()
Solution 2:
Using the Fisher-Yates shuffle I have created a small script for this purpose. This is done by first creating a randomly shuffled and sliced copy of the array of jQuery elements, and then filtering out all elements that do not exist in both arrays.
You can read about it at http://www.afekenholm.se/jquery-rand. Here's the script:
/**
* jQuery.rand v1.0
*
* Randomly filters any number of elements from a jQuery set.
*
* MIT License: @link http://www.afekenholm.se/license.txt
*
* @author: Alexander Wallin (http://www.afekenholm.se)
* @version: 1.0
* @url: http://www.afekenholm.se/jquery-rand
*/
(function($){
$.fn.rand = function(k){
var b = this,
n = b.size(),
k = k ? parseInt(k) : 1;
// Special cases
if (k > n) return b.pushStack(b);
else if (k == 1) return b.filter(":eq(" + Math.floor(Math.random()*n) + ")");
// Create a randomized copy of the set of elements,
// using Fisher-Yates sorting
r = b.get();
for (var i = 0; i < n - 1; i++) {
var swap = Math.floor(Math.random() * (n - i)) + i;
r[swap] = r.splice(i, 1, r[swap])[0];
}
r = r.slice(0, k);
// Finally, filter jQuery stack
return b.filter(function(i){
return $.inArray(b.get(i), r) > -1;
});
};
})(jQuery);
Solution 3:
Get a random number index, 1-5, and get the child of the ul with that index. Like so:
var index = Math.floor(Math.random() * 5) + 1; // nth-child indices start at 1
alert($("ul:nth-child(" + index + ")").text());
Solution 4:
jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"], {
random: function(a, i, m, r) {
if (i == 0) {
jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
};
return i == jQuery.jQueryRandom;
}
});