I was wondering if there is a way to have JQuery randomly select a li
inside a ul
tag.
Example:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
So here is what would happen, lets have a click event so, $("ul li:last").trigger('click');
but notice how it has :last
, how could I specify whether it selects the second, third, or even the fourth li
based in the tree randomly.
UPDATE:
I notice other suggested using math, what if I have a ul li
list that is populated by MySQL, I wouldn't know how many li
there would be.
Use
Math.floor( (Math.random() * $('ul li').length) + 1 );
This gives you a number between 1 and the number of li
, then use the :nth-child()
selector.
You can learn more about that here
Here is a extension function
$.fn.random = function()
{
var ret = $();
if(this.length > 0)
ret = ret.add(this[Math.floor((Math.random() * this.length))]);
return ret;
};
This is how you would use it
$("ul li").random().trigger("click");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With