Brian
Brian

Reputation: 3958

Use javascript to randomly append CSS class to one list item

Hey, I don't have any code because I don't know how to do this. I'm looking to use jQuery / javascript to randomly append the CSS class "active" to one list item within a an unordered list id'd as ul#sliding_panels.

Upvotes: 2

Views: 2391

Answers (3)

Mathieu
Mathieu

Reputation: 5695

var elements = $('ul#mylist li');
$ (elements.get (
  Math.round (elements.length*Math.random ()-0.5)
)).addClass ('active');

Upvotes: 1

cletus
cletus

Reputation: 625087

Keep it simple. This retrieves all the list items under that list:

var items = $("#sliding_panels li");

Then use Math.random() to pick one of them. Note: the construct Math.floor(Math.random() * 10)) will return an integer between 0 and 9 inclusive.

var item = Math.floor(Math.random() * items.length);

You can use the array index operator on a jQuery object to retrieve one of those elements. Note: set[n] is equivalent to set.get(n) if set is a jQuery object.

You then need to wrap that element in a jQuery object and use addClass():

$(items[item]).addClass("active");

Upvotes: 4

Nick Craver
Nick Craver

Reputation: 630429

See this question for how to grab a random element.

$("#sliding_panels li").get().sort(function(){ 
  return Math.round(Math.random())-0.5
}).slice(0,1).addClass("active");

Credit to duckyflip for the original answer.

An alternative is the :random plugin mentioned in the same question.

Example:

$("#sliding_panels li:random").addClass("active");

Upvotes: 1

Related Questions