Javascript: Random Image Generator

Posted by on November 11, 2013 • Filed Under Tutorials

I wrote a tutorial on generating random links with javascript some months ago. Recently, a person requested to show how to show this method but with images. This is why I’m writing this tutorial about how to create a random image generator.

The first thing you need to do is create an array with the URLs of the images you’re going to use. There are two common ways to do this, as you saw on the random link tutorial.

The condensed array:

Or the regular array:

You can use any of these two methods. The next step is to create the function that will generate the images using a native random method.

And that’s it! All that’s left for you to do is to combine all the code (showed below), which would display the image and every time you refresh the page, a random image from your array will appear.


Here’s the complete code:


If you have any questions, don’t hesitate to leave a comment.



  • avatar image


    Nov 11, 2013


    I was actually going to ask about this on the Byte Sized forum the other day, then I forgot. So this is SUPER helpful as I don't want to install a plugin for something code can do.

  • avatar image


    Nov 12, 2013


    Thanks for posting this! This is really helpful. :)

  • avatar image

    Bashir Keber

    Dec 14, 2017


    How can I add images and show it

  • avatar image


    Aug 15, 2018


    Thanks alot

Post your comments