Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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)functionsetRandomClass() {
    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

Solution 2:

Could do something like this:

HTML

<ulid="randomCol"><li>test1</li><li>test2</li><li>test3</li><li>test4</li><liclass="color">test5</li><li>test6</li><li>test7</li><li>test8</li><li>test9</li><li>test10</li></ul>

Jquery

var tid = setInterval(changeUp, 1000);
functionchangeUp() {
  var i = Math.floor((Math.random()*9));
  $('#randomCol').children().removeClass('color');
   $('#randomCol').children().eq(i).addClass('color');
}

fiddle

Post a Comment for "Continuously Add And Remove Class To A Random Element With Jquery"