11

I have a bunch of divs with the ID "gallerycard". I need them to load in a random order every time the user visits the page.

<div id="gallerycard">
     <div id="name">Akulina</div>
    <div id="info">N/A</div>
</div>

<div id="gallerycard">
     <div id="name">Martina</div>
    <div id="info">N/A</div>
</div>

<div id="gallerycard">
     <div id="name">Joseph</div>
    <div id="info">N/A</div>
</div>

<div id="gallerycard">
     <div id="name">Karen</div>
    <div id="info">N/A</div>
</div>
...    

And...

Here's the fiddle with CSS: http://jsfiddle.net/BwJHj/

I know this is a simple task for most of you but I really struggle with jquery at times :(

Thank you

arauzo
  • 185
  • 1
  • 7
user2724603
  • 113
  • 1
  • 1
  • 4

1 Answers1

23

HTML

First change all of the ids to classes since id must be unique on a page.

<div class="gallerycard">
     <div class="name">Akulina</div>
    <div class="info">N/A</div>
</div>

<div class="gallerycard">
     <div class="name">Martina</div>
    <div class="info">N/A</div>
</div>

<div class="gallerycard">
     <div class="name">Joseph</div>
    <div class="info">N/A</div>
</div>
...    

CSS (Since markup now uses classes switch the style to reflect)

.gallerycard {
    margin: 8px;
    float: left;
    height: 150px;
    width: 221px;
    background-color: rgba(0, 0, 0, .3);
    border-radius: 8px;
}

Javascript

Select all card elements from the DOM then generate two randoms between 0 and cards.length. Use eq to select a random element in the selected elements and position it before another randomly selected element in the set of selected eleemnts.

var cards = $(".gallerycard");
for(var i = 0; i < cards.length; i++){
    var target = Math.floor(Math.random() * cards.length -1) + 1;
    var target2 = Math.floor(Math.random() * cards.length -1) +1;
    cards.eq(target).before(cards.eq(target2));
}

JS Fiddle: http://jsfiddle.net/BwJHj/1/

arauzo
  • 185
  • 1
  • 7
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Wow, that's actually a pretty weird way to shuffle: you change order of a randomly taken element `length` times instead of just giving each `i`-th element a new random position. If it stays this way, only in best case scenario all elements will be shuffled, but most times there will be _gaps_ of elements that stayed on the original place. – Klesun Oct 25 '20 at 17:15