2

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.

Brian
  • 3,920
  • 12
  • 55
  • 100

3 Answers3

4

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
  • 616,129
  • 168
  • 910
  • 942
1

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");
Community
  • 1
  • 1
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
1
var elements = $('ul#mylist li');
$ (elements.get (
  Math.round (elements.length*Math.random ()-0.5)
)).addClass ('active');
Sasha Chedygov
  • 127,549
  • 26
  • 102
  • 115
Mathieu
  • 5,495
  • 2
  • 31
  • 48