Tom S. Tom S. - 2 months ago 22
jQuery Question

Continuously add and remove class to a random element with jQuery

Let's say I have an unordered list of ten elements.

I'd like a class to be added to one of them at random, and then remove that class after a couple of seconds and start again with another randomly chosen element indefinitely.

What would be the cleanest way to achieve that?

edit:
What I've got so far:

<ul id="hideAndSeek">
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
...
</ul>


And the jQuery:

var random = Math.floor(Math.random() * 1000);

var shownElement = $("#hideAndSeek li");
shownElement.eq(random % shownElement.length).addClass("shown");


However, this obviously does not run continuously, and I don't know how to properly set a delay before removing the class.

Answer

You need to use setInterval to create a timer, and then you can choose a random number and set the class for that item index.

Something like this:

HTML

<ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
    <li>four</li>
    <li>five</li>
    <li>six</li>
    <li>seven</li>
    <li>eight</li>
    <li>nine</li>
    <li>ten</li>
</ul>

Javascript (w/ JQuery)

setRandomClass();
setInterval(function () {
    setRandomClass();
}, 2000);//number of milliseconds (2000 = 2 seconds)

function setRandomClass() {
    var ul = $("ul");
    var items = ul.find("li");
    var number = items.length;
    var random = Math.floor((Math.random() * number));
    items.removeClass("special");
    items.eq(random).addClass("special");
}

Here is a working example