-1

I have a <ul> with over 6 <li> elements. I only want to show only 6 at time. The trick is I need it to randomly select which elements to hide, and to stagger the hide/show.

For example my current markup :

<ul>
<li>1<li>
<li>2<li>
<li>3<li>
<li>4<li>
<li>5<li>
<li>6<li>
<li>7<li>
<li>8<li>
<li>9<li>
</ul>

Is it possible to use jQuery to hide/show the elements to provide something random like this:

<ul>
    <li style="display:none">1<li>
    <li>2<li>
    <li style="display:none">3<li>
    <li>4<li>
    <li>5<li>
    <li>6<li>
    <li>7<li>
    <li style="display:none">8<li>
    <li>9<li>
 </ul>
Sam
  • 5,150
  • 4
  • 30
  • 51
  • 2
    Absolutely, but as I'm sure you know we're not here to write code for you...only help you fix code that you can't get to work. What have you tried so far? – Paulie_D Jul 23 '15 at 17:11
  • Found answer here: http://stackoverflow.com/questions/18101314/continuously-add-and-remove-class-to-a-random-element-with-jquery – Sam Jul 23 '15 at 19:23

1 Answers1

0

You really should try to do things before posting questions here, then include the code you have tried to show that you actually have tried. However, as this is fairly simple, I'll answer your question.


Expanding on this answer to a question about generating random numbers in JavaScript, you can use a while() loop to generate a random number between 0 and the number of elements minus 6.

We don't want to hide the same element twice, so we have to check if the element with the same index as the random number is hidden.

  • If it is visible, hide it and reduce the number of further iterations by 1
  • If it is hidden, do nothing and start a new iteration.

(Demo)

var items = document.querySelectorAll("#random li"), index, i;
var min = 0;
var max = items.length - 1;
var count = items.length - 6;

while(count > 0) {
    index = Math.floor(Math.random() * (max - min + 1)) + min;
    if(items[index].style.display != "none") {
        items[index].style.display = "none";
        --count;
    }
}

Code Correction:

You should use closing tags to end your HTML elements.

<li>2<li>

Should be

<li>2</li>
Community
  • 1
  • 1