Something missing from jQuery?
Getting somewhat spoiled with Ruby, I was surprised jQuery didn’t have a
function akin to Ruby’s sample
. Of course it’s easy enough to implement
on your own, but why not include it in the library?
$.fn.random = function() {
var ret;
ret = $();
if (this.length > 0) {
ret = ret.add(this[Math.floor(Math.random() * this.length)]);
}
return ret;
};
or if you prefer coffeescript:
$.fn.random = ->
ret = $()
if @length > 0
ret = ret.add(@[Math.floor(Math.random() * @length)])
ret
My usecase for this was something like the following: I have many accordions with collapsed panels, and I want one random panel in every accordion to be expanded.
$('[id^="accordion"]').find('.panel-collapse').random().addClass('in')
Comments