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.
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
Javascript (w/ JQuery)
Here is a working example
Could do something like this:
HTML
Jquery
fiddle