How to add a full page background image to your landing page

I recently decided to update the landing page of one of my projects. I wanted to have a full-page background image and change this background image every time a user landed in this page or refreshed it. Here is what I ended up doing:

The <html> tag

Since we are replacing the entire background of your page, let’s add the background image to your html tag. We are going to do this by using some JavaScript that will update the <html> style when the page loads. The reason I am doing this instead of using CSS is because I want to be able to change the background image every time the page loads or it is refreshed.

The first step is to add an id to the <html> tag as shown below:

<html lang="en" id="landing">

Adding an id to the <html> tag allows us to identify it when doing the image background change in JavaScript.

The JavaScript

In order to display a different image every time the page loads or gets refreshed I wrote a function that randomly picks one image from an array. Basically I look at the length of the array (# of images) and then just pick a number from the array using both the Math.floor and Math.random methods from JavaScript.

The last step is to change the background image style of <html> to be the current selected image from JavaScript as shown below:

// <![CDATA[
  function Randomize() {
     var images = new Array("/images/journal1.jpg",
         "/images/journal4.jpg",
         "/images/journal6.jpg",
         "/images/journal7.jpg",
         "/images/journal8.jpg",
         "/images/journal9.jpg",
         "/images/journal10.jpg",
         "/images/journal12.jpg",
         "/images/journal13.jpg",
         "/images/journal14.jpg");
     var imageNum = Math.floor(Math.random() * images.length);
     document.getElementById("signup").style.backgroundImage = "url('" + images[imageNum] + "')";
  }
  window.onload = Randomize;
// ]]>

If you haven’t already I suggest you place your images and any other static content in a CDN. If you have Azure, take a look at my previous post where I explain how to serve static files from Azure.

Please share your comments or feedback in the comments section below. Happy coding!