Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting a random li element - JQuery

Tags:

jquery

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.

like image 651
David Biga Avatar asked Nov 27 '22 21:11

David Biga


2 Answers

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

like image 171
Aarón Cárdenas Avatar answered Dec 03 '22 02:12

Aarón Cárdenas


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");
like image 40
John Avatar answered Dec 03 '22 01:12

John