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.
Try below,
var $hiddenSlides = $('div.slideshow').find('div.slide:hidden');
var length = $hiddenSlides.length;
var ran = Math.floor(Math.random()*length );
var newSlide = $hiddenSlides.get(ran);
How about this:
var $hiddenSlides = $('div.slideshow').find('div.slide:hidden');
var ran = Math.floor(Math.random()*$hiddenSlides.length);
var newSlide = $hiddenSlides.get(ran);
$("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();
});
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.
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?
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();