Skip to content Skip to sidebar Skip to footer

Display Images In Order Rather Than By Random Using Js?

Listed below in the block of code is Math.random. I'm trying to display images every time the page is refreshed or reloaded. Though, the only way I know is to mathmatically load th

Solution 1:

Put the array index in a cookie or local storage. When the page loads, get the cookie, and increment it (if it's not set this is the first time, so select an image at random). If the increment reaches the size of the array, wrap around to 0. Then display the image with that index. Then save the new cookie value.

var imageArray = [
    [ 'http://example.com/assets/reporter.png', '<style>body{background-image:url(), -webkit-linear-gradient(#f5eddf 0%, #e3cfad 100%);#image{margin-left:500px;}</style>', '' ],
    [ 'http://example.com/assets/chair.png', '<style>body{background-image:url(), -webkit-linear-gradient(#7abbe7 0%, #a7dbfa 100%);}</style>', '' ]

];

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function doIt()
{
    var rand = getCookie('rand');
    if (rand == null) {
        rand = Math.floor(Math.random()*imageArray.length);
    } else {
        rand++;
        if (rand >= imageArray.length) {
            rand = 0;
        }
    }
    setCookie('rand', rand);
    var html = "<a href='"+imageArray[rand][2]+"'><img src='"+imageArray[rand][0]+"' alt='heder' border='0' align='absmiddle' /></a><div>"+imageArray[rand][1]+"</div>";

    document.getElementById("image").innerHTML = html;
}​

Post a Comment for "Display Images In Order Rather Than By Random Using Js?"