Menu

How to load random images on page load (with jQuery)

Today I’m going to show you a quick tutorial on how to load random content on page load using a little HTML and jQuery.

In this example, we’re going to use images as our random content, which can be the right solution for you if you have promotional content to serve your users but not a lot of real estate in your design. It can also be an effective method for displaying content that may be more ad-based without ending up with pages that are lathered in ads. Clutter just ain’t right.

Using jQuery, we use the following to determine both the individual images we’re going to load randomly and which element on your page it will be loaded in. This example uses four images.

var image = new Array ();
image[0] = "/path/to/image1.jpg";
image[1] = "/path/to/image2.jpg";
image[2] = "/path/to/image3.jpg";
image[3] = "/path/to/image4.jpg";
var size = image.length
var x = Math.floor(size*Math.random())

$('#randomImages').attr('src',image[x]);

Now we need assign the ID ‘randomImages’ to the element on our page where we wish them to display:

<img id="randomImages" alt="#">

One thing you may likely notice is that the ALT attribute remains the same for each image in this example. This can be a potential Accessibility issue for you in the event that any image doesn’t load for whatever reason.

If you are using this in your WordPress theme, you will need to include the full path to your content in the script, beginning with https://.

Have fun!

Archived under:
Share:
This site uses cookies to collect basic info to help improve your experience. Read my Privacy Policy Accept