Search code examples
jqueryrandomhref

Random href attribute in website address


I am creating one website that uses CSS3 fullscreen gallery. Basically, when i change images my website's address changes. For example, http://www.mysite/index.html#image7 or http://www.mysite/index.html#image20.

I would need a way to display a random image on page load with jQuery or pure JS. I can point to an exact image easily with having this line inside document ready function:

document.location.href = "http://www.mysite/index.html#image13";

I am not so good with JavaScript, but maybe creating some array of images and then using some randomize function would do the trick?

Any advice?


Solution

  • Ok, i managed to do it myself. I stored some values into an array, and then just used it with document.location.href

        var images = [],
            index = 0;
    
            images[0] = "http://www.mysite/index.html#image13";
            images[1] = "http://www.mysite/index.html#image17";
            images[2] = "http://www.mysite/index.html#image5";
    
            index = Math.floor(Math.random() * images.length);
    
            document.location.href = images[index];