Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created May 10, 2011 16:27
Show Gist options
  • Save cowboy/964822 to your computer and use it in GitHub Desktop.
Save cowboy/964822 to your computer and use it in GitHub Desktop.
jQuery Random: Add an "element of surprise" into the chain!
/*!
* jQuery Random - v0.1 - 5/10/2011
* http://benalman.com/
*
* Copyright (c) 2011 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($){
$.fn.random = function() {
// The result set.
var elems = [];
// Select all elements currently in the DOM.
var all = $('*');
// For each selected element...
return this.each(function() {
// Push a random element onto the result set.
elems.push(all[~~(Math.random() * all.length)]);
// And return a new set that's revertable with .end().
}).pushStack(elems);
};
})(jQuery);
// jQuery Random v0.1, 5/10/2011, http://benalman.com/ Copyright (c) 2011 "Cowboy" Ben Alman, dual licensed MIT/GPL.
;(function(a){a.fn.random=function(){var b=[],c=a("*");return this.each(function(){b.push(c[~~(Math.random()*c.length)])}).pushStack(b)}})(jQuery);
@jupiterjs
Copy link

Nice use of the bitwise not! Didn't think to use it like that. Now I can save some chars (while probably confusing people).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment