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.
3 Answers
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");
Comments
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");