Question

I'm attempting to make a button display random element when clicked using show/hide. It sets up so the element will be hidden first to stop duplicates, then shown. However it sometimes doesn't show.

The Fiddle will be clearer than my explanation: http://jsfiddle.net/qAfqN/.

Simplified code:

    this.uiSelect = function(){
    var length = $("#ui li").length;
    var ran = Math.floor(Math.random()*length);
        $('#ui li').hide();
    $("#ui li:nth-child(" + ran + ")").show();
};

    $(document).ready(function(){   
    $('#mangle').click(function(){
        uiSelect();
    }); 
});
Was it helpful?

Solution

Use :eq() instead of :nth-child(). They have quite a different meaning. The former refers to the element's position in the jQuery collection, while the latter refers to its position among its DOM siblings. These are not the same in your situation.

Consider the following markup:

 div
    > ul
        > li 1
        > li 2
    > ul
        > li 3
        > li 4
        > li 5

The query $('div li:eq(2)') will return li 3 (indices are zero-based), because that is the third element in the collection. On the other hand, $('div li:nth-child(3)') (indices are one-based here, that is why I wrote 3 instead of 2) will return li 5, because that is the only third element in its group, among its siblings.

You can even save yourself some ugly string concatenation and duplicate DOM lookups if you use .eq() instead of :eq() and some chaining like this:

$("#ui li").hide().eq(ran).show();

jsFiddle Demo

OTHER TIPS

Try this one, but I am not sure if this is what you want http://jsbin.com/ibasuv/1/edit

var pickRandom = function(selector){
  var lis = $(selector).find('li');
  lis.hide();

  var size = lis.size();

  var random = Math.floor(Math.random()*size);
  $(selector).find('li').eq(random).show();
};

I put a div closing tag for the second div, I think

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top