Jadeja Rahulsinh
Jadeja Rahulsinh

Reputation: 57

Show random div without particular class using jQuery

I've dynamic list and I'm displaying it in div as below

<div class="cards card1">       
  <div class="front">
    <p>Front 1</p>
  </div>
  <div class="back1" style="display: none">
    <p>Back 1</p>
  </div>
</div>

<div class="cards card2" style="display: none">     
  <div class="front">
    <p>Front 2</p>
  </div>
  <div class="back2" style="display: none">
    <p>Back 2</p>
  </div>
</div>

<div class="cards card3" style="display: none">     
  <div class="front">
    <p>Front 3</p>
  </div>
  <div class="back3" style="display: none">
    <p>Back 3</p>
  </div>
</div>

Now when page loads it only shows first main div (card1). I've one button named "Show". When I click on that it shows second subdiv (back1) of first main div using jQuery. it also adds one class to main div(card1) named 'visited'.

There's also one other button named "Next". Now what I want to do is when I click on this "Next" button I want to shuffle remaining divs (card2, card3) and show randomly div from these two divs. During shuffling it should only shuffle divs that don't have that 'visited' class.

So suppose I clicked reveal button for the first div. 'visited' class will be added to that div (card1). Now there's two divs remaining which don't have class 'visited'. So when I'll click "Next" button it should show card2 or card3 div only not the card1 because card1 contains 'visited' class.

After that suppose card3 div appears and I again click on "Next" button. Then it should show me card3 div because it's only div that doesn't contain 'visited' class.

I've so many this type of divs. Remember the card should be shuffled (random).

Please help me with this.

Upvotes: 1

Views: 149

Answers (1)

Ezphares
Ezphares

Reputation: 359

JQuery has a not() selector to filter an existing query. Then you can use the method from this answer to select a random element. Put together:

let unvisited = $('.cards').not('.visited');
let next_card = unvisited.eq(Math.floor(Math.random(unvisited.length)));
next_card.show();

Upvotes: 1

Related Questions