views:

168

answers:

3

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.

+1  A: 

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");
Nick Craver
I don't get this. Why sort for selecting a random element? It's weird.
cletus
seems a bit overkill ..
Gaby
+4  A: 

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");
cletus
+1  A: 
var elements = $('ul#mylist li');
$ (elements.get (
  Math.round (elements.length*Math.random ()-0.5)
)).addClass ('active');
mathroc