How can I return a random element in jQuery by doing something like $(.class).random.click()
?
So, if .class
had 10 links, it would randomly
You can write a custom filter (taken from here):
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;
}
});
Example usage:
$('.class:random').click()
The same thing but as a plugin instead:
jQuery.fn.random = function() {
var randomIndex = Math.floor(Math.random() * this.length);
return jQuery(this[randomIndex]);
};
Example usage:
$('.class').random().click()
randojs.com makes this a simple one-liner:
rando($("a")).value[0].click()
The ".value" is there because you also have the option to get the index of the random jQuery element. The "[0]" is there to turn the jQuery element into a plain JavaScript element. If you add the following to the head of your html document, you can do pretty much whatever you want with randomness easily. Random values from arrays, random jquery elements, random properties from objects, and even preventing repetitions if needed.
<script src="https://randojs.com/1.0.0.js"></script>
I'd suggest doing it the jQuery way using .eq()
and .trigger()
.
$elements.eq(Math.floor(Math.random() * $elements.length)).trigger('click');
You can select random item by class name using jquery method eq()
see the example bellow.
var len = $(".class").length
var random = Math.floor( Math.random() * len ) + 1;
$(".class").eq(random).click();
If you don't want to hard code the number of elements to choose from, this works:
things = $('.class');
$(things[Math.floor(Math.random()*things.length)]).click()
var random = Math.floor(Math.random()*10);
$(".someClass").eq(random).click();