Find hidden elements and store them in an array

Go To StackoverFlow.com

0

I have some mark-up like so:

<div class="slideshow">
    <div class="slide" style="display:block;"></div>
    <div class="slide" style="display:none;"></div>
    <div class="slide" style="display:none;"></div>
    <div class="slide" style="display:none;"></div>
</div>

Which is basically some divs with one shown and the others hidden.

I'm trying to find the ones that are currently not shown and then randomly select one of them...

var length = $('div.slideshow').find('div.slide:hidden').length;

var ran = Math.floor(Math.random()*length) + 1;
var newSlide = $("div.slideshow > div.slide:nth-child(" + ran + ")");

However because their is more than one hidden div it will not work... I'm guessing I need to setup an array? Can anyone help me out here as I'm a little confused.

2012-04-05 14:51
by Cameron


3

Try below,

DEMO

var $hiddenSlides = $('div.slideshow').find('div.slide:hidden');
var length = $hiddenSlides.length;

var ran = Math.floor(Math.random()*length );
var newSlide = $hiddenSlides.get(ran);
2012-04-05 14:58
by Selvakumar Arumugam


1

How about this:

var $hiddenSlides = $('div.slideshow').find('div.slide:hidden');
var ran = Math.floor(Math.random()*$hiddenSlides.length);
var newSlide = $hiddenSlides.get(ran);
2012-04-05 15:02
by Josh Siok


0

$("div.slideshow > div.slide:nth-child(" + ran + ")" selects from all children, including the one that is already visible. Do you want that?

If so, you have to iterate your selection with

$("div.slideshow > div.slide:nth-child(" + ran + ")").each(function() {
    $(this).show();
});
2012-04-05 14:57
by Frank van Wijk


0

This should work for you:

var length = $('div.slideshow').find('div.slide:hidden').length;
var ran = Math.floor(Math.random()*length);
var newSlide = $(".slideshow .slide:hidden:eq(" + ran + ")");

You'll see in this jsFiddle that the output is always one of the hidden divs.

2012-04-05 15:00
by j08691


0

explanation:

it won't work because the order of elements is not guaranteed, why not iterate over the elements using the same selector you applied to find the hidden elements?

example:

save the visible element:

var shownSlide = $("div.slideshow > div.slide:visible");

apply the random traversal:

var ran = Math.floor(Math.random()*length) + 1;
$("div.slideshow > div.slide:hidden:eq(" + ran + ")").show();

than re-hide the visible element:

$(shownSlide).hide();
2012-04-05 15:01
by Eliran Malka
Ads