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
HTML
First change all of the id
s 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With