Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Div Order on Page Load [duplicate]

Tags:

html

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

like image 209
user2724603 Avatar asked Aug 28 '13 08:08

user2724603


1 Answers

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/

like image 79
Kevin Bowersox Avatar answered Sep 22 '22 09:09

Kevin Bowersox