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.

3 Answers 3

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");
Sign up to request clarification or add additional context in comments.

Comments

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");

1 Comment

I don't get this. Why sort for selecting a random element? It's weird.
1
var elements = $('ul#mylist li');
$ (elements.get (
  Math.round (elements.length*Math.random ()-0.5)
)).addClass ('active');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.