Edit: let me try to do this again, sorry I'm not good at explaining things through text only

  1. I have an unordered list
  2. I'd like only a random one of the list items to appear
  3. When a button is clicked, a different random item replaces the one already displayed

The list items are already dynamically added through with PHP, thus it would be great if that didn't have to be changed.

I wrote up a visual demo here: http://jsbin.com/opupe3/edit

2 answers

This was chosen as the best answer

I usually add a :random pseudo-selector to jQuery if I'm going to use it more than once, but for a one-off randomization, something like this should do the trick:

jQuery(function($) {
        $$ = $(".target li");
        $$.hide().eq(Math.floor(Math.random() * $$.length)).show();

This one works by hiding all list items in your target, then showing one item at random. Replace ".button" with a CSS selector that will grab your button/link. Replace ".target li" with a CSS selector to grab all of your list items.

Try it out on JS Bin

Full code:

<!DOCTYPE html>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
            /* this glorious hack by bobthecow (http://bobthecow.info) */
            jQuery(function($) {
                    $$ = $(".target li");
                    $$.hide().eq(Math.floor(Math.random() * $$.length)).show();
        <ul class="target">
        <button class="button">Click Me</button>
Answered over 9 years ago by Justin Hileman
Mottie 1134

This is how I would do this using jquery (it just makes life easier)


.ideas { display: none; }


<a class="newidea">Give Me Another</a>
<ul class="ideas">
 <li>random 1</li>
 <li>random 2</li>
<div id="idearotator"></div>

Script (including the jQuery library)

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
 $('.newidea').click(function(){ updateidea() });
function updateidea(){
 var idea = $('.ideas li');
 var pick = Math.round(Math.random()*(idea.length - 1));
 $('#idearotator').html( $(idea[pick]).html() );
Answered over 9 years ago by Mottie
  • Unfortunately it doesn't really work. 1. the idearotator div is still empty when begins 2. if i hide the ideas list, it only works once learning js + jquery is on my to-do list though =] and thanks for the response! Andy Zhang over 9 years ago