myh_stack
myh_stack

Reputation: 35

Showing random divs images every time page is load

Lets say I have these images gallery, how do i randomly display the images everytime when i reload the page?

http://creativepreviews.com/fiddle/study/20131007/

Upvotes: 1

Views: 1315

Answers (2)

roryrjb
roryrjb

Reputation: 889

Let's say the image will display in the background of the DIV, then the following should do it.

// JS

var imgArray = ["img1.jpg", "cat.jpg", "sky.jpg"]

function randomBg() {
    x = Math.random()
    y = Math.round(x * 10)
    if (imgArray[y] != undefined) {
        document.getElementById("blah").style.backgroundImage = "url('" + imgArray[y] + "')"
    } else {
            document.getElementById("blah").style.backgroundImage = "url('default.jpg')"
    }    
}

...and the HTML.

<script src="test.js"></script>
<body onload="randomBg()">
<div id="blah"></div>

...or you could replace the style.backgroundImage in the JS with innerHTML = <img src=" etc...

Upvotes: 1

DroidOS
DroidOS

Reputation: 8890

You could do something along these lines (not tested)

var grd = $('#grid');
var imgs = grd.children();
imgs.sort(function(){return (Math.round(Math.random()) - 0.5);});
grd.remove('li');
for(var i=0;i < imgs.length;i++) grd.append(imgs[i]);

In essence what we are doing is getting all the li elements in 'grid' into an array, randomizing them, removing them all from 'grid' and then putting them back in again.

If you had supplied a working fiddle rather than a link to the finished article it would be easier to modify it and provide a more complete solution.

Upvotes: 0

Related Questions