Tom S. Tom S. - 1 year ago 105
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?

What I've got so far:

<ul id="hideAndSeek">

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 Source

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:



Javascript (w/ JQuery)

setInterval(function () {
}, 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));

Here is a working example

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download