0

I have some images:

http://snag.gy/xsm7N.jpg

I want to make the images in a random order every time someone refreshes the page.

Basically, the images should switch spots every time someone refreshes.

How do I do this? I've searched but can't seem to find much.

I also want the images to link to a website.

BTW, I use Smarty for my page layout.

2 Answers2

0

You can use something like this:

<script type="text/javascript">


window.onload = function() {
  randomlinks();
};

function randomlinks(){
    var myrandom=Math.round(Math.random()*9)
    var links=new Array()
    links[0]="http://www.iamurl.xyz/1.jpg"
    links[1]="http://www.iamurl.xyz/2.jpg"
    links[2]="http://www.iamurl.xyz/3.jpg"
    links[3]="http://www.iamurl.xyz/44.jpg"
    links[4]="http://www.iamurl.xyz/43.jpg"
    links[5]="http://www.iamurl.xyz/12.jpg"
    links[6]="http://www.iamurl.xyz/11.jpg"
    links[7]="http://www.iamurl.xyz/11.jpg"
    links[8]="http://www.iamurl.xyz/133.jpg"
    links[9]="http://www.iamurl.xyz/112.jpg"
    links[10]="http://www.iamurl.xyz/111.jpg"


    window.location=links[myrandom]
}
</script>
Abey
  • 1,408
  • 11
  • 26
0

You can use arrays to do it. However, you must use a shuffling method for this array. Then you can tour the new randomized array to create the HTML string. You could do it this way:

//https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
Array.prototype.shuffle=function(){var i=this.length,j,temp;if(i==0)return this;while(--i){j=Math.floor(Math.random()*(i+1));temp=this[i];this[i]=this[j];this[j]=temp}return this}

var images = [
    {url: "1.gif", link: "http://www.google.com"},
    {url: "2.gif", link: "http://www.youtube.com"},
    {url: "3.gif", link: "http://www.facebook.com"}
];
var imagesShuffle = images.shuffle();

var elementParent = document.querySelector("#images");

imagesShuffle.forEach(function(image){
    elementParent.innerHTML += '<div class="imageItem"><a href="'+image.link+'"><img src="'+image.url+'" alt="'+image.url+'"></a></div>'
})
#images{background:#BC4F0A; width:200px}

#images .imageItem {border-bottom:1px solid black}

#images .imageItem a {display:block;padding:15px 10px; }
<div id="images"></div>
Community
  • 1
  • 1