The Blog

JavaScript: Random Background Colors and Images

Mar 19, 2018 | Coding, Web Design

We implemented something a little bit fun on our site recently. Using JavaScript, our front page header, and certain sections of the site load a random background image or colour when you load the page. Read on to find out how we did it.

Actually, the image above has a dynamically changing background. There are four variations, and if you refresh the page a couple of times you should see the background change.

How it’s done

Below is the full code we used to implement our random backgrounds. I will explain each part separately afterwards.

Fig 1. Full code


window.onload = function () { 
 var myBody = document.querySelectorAll(".changeBgCol"); 
 var myHeader = document.querySelector(".changeBgPic");
 var colArray = new Array("486bce","ebb7a7", "da945c", "1d7d6d"); 
 var imgArray = new Array("img_url_1", "img_url_2", "img_url_3", "img_url_4");
 var spot = Math.floor(Math.random()* colArray.length); 
 
 for (var i = 0; i < myBody.length; i++) {
 myBody[i].style.backgroundColor = "#"+colArray[spot];
 }

 myHeader.style.background = "url("+imgArray[spot]+")";
}

 

Basic overview

What we want is to have our page display a random background out of a predefined set each time the page is loaded. We also want a background colour matching the image to be applied to specific sections of the page.

A function is created to trigger when the web page is loaded. Within that function variables are created:

myBody – selects all elements with the HTML class of changeBgCol.

myHeader – selects the element with the HTML class changeBgPic.

colArray – an array containing all of the hex codes for the colours we want to potentially apply to our changeBgCol elements backgrounds.

imgArray – an array containing all of the background image urls we want to potentially apply to our changeBgPic element’s background.

spot – generates a random number from 0 to 3. This is the length of our colArray array. This is also the length of our imgArray array, as we have set 4 items for each in order to match the colours to the backgrounds. Arrays are zero based and so are counted 0, 1, 2, 3 for four items.

In the below code block I have shown only the variables we created:

Fig 2. The variables


 var myBody = document.querySelectorAll(".changeBgCol"); 

 var myHeader = document.querySelector(".changeBgPic");

 var colArray = new Array("486bce","ebb7a7", "da945c", "1d7d6d"); 

 var imgArray = new Array("img_url_1", "img_url_2", "img_url_3", "img_url_4");

 var spot = Math.floor(Math.random()* colArray.length); 

 

Note: The colour you want to match to a specific background should be at the same position in the array as that background. As per the example above, when img_url_1 is applied to changeBgPic (myHeader), we want #486bce applied to changeBgCol (myBody), and so both are listed first in our two arrays.

You will also need to replace img_url_1img_url_2, and so forth with the urls of your own background images, and the same with the hex codes for your colours.

The for loop and applying the background colour

Now that we have our variables set up for the images and colours we want to apply and which elements we want to apply them to, we just have to use a simple for loop and some basic CSS manipulation.

Because we used document.querySelectorAll when creating our myBody variable, we now have an array containing each instance of the changeBgCol class on the page.

This means that we can cycle through them with a for loop, applying our background colour to each, and the loop will end once there are no more instances of that class to apply the colour to.

Fig 3. Applying background colour to multiple elements with the for loop


for (var i = 0; i < myBody.length; i++) {
 myBody[i].style.backgroundColor = "#"+colArray[spot];
 }

 

A basic explanation of the above for loop:

  • We create a variable called i and set it to 0.
  • We say that while i is less than the length of myBody (which is the amount of elements with the class changeBgCol on the page), it should run the code within the curly braces and then add 1 to i .
  • Once i is no longer less than the length of myBody, the loop will finish.

Note: The reason we want the loop to stop running before i is equal to the length of myBody is because arrays are zero based.

The code inside the curly braces – myBody[i].style.backgroundColor = “#”+colArray[spot]; is explained below:

  • myBody[i]. – As the loop runs this will translate to myBody[0], myBody[1], myBody[2] … and so on, until it has run through the number of elements on the page with the class changeBgCol.
  • style.backgroundColor = “#”+colArray[spot]; – Sets the CSS background colour generated from our random number ( spot ) . For example, if our random number is 2, this will translate as the CSS code:

 background-color: #da945c;
 

Applying the background image

The last thing to happen in this function is applying our background image to the class changeBgPic ( myHeader ).

Fig 4. Applying the background image


myHeader.style.background = "url("+imgArray[spot]+")";

 

This works in exactly the same way as applying our background colour, except we don’t need the for loop because we only ever have one element with the class changeBgPic. The random number ( spot ) is used in both, and so as long as you have your matching background image and colour at the same position in each array ( colArray and imgArray ), they will display together.

As per the above example pertaining to applying the background colour – if our random number is 2 this will translate to the CSS code:


 background: url("img_url_3");
 

Conclusion

We have applied a fallback background colour of #333333 to both our changeBgCol and changeBgPic classes in our stylesheet. Should something not work, the text will not be unreadable and there will be a simple background colour in place of our dynamic image and colours.

The great thing about this code is that should you decide to remove a image and colour set from the code, or add a new one, you will not need to change any other part of the code.

You can also apply the changeBgCol class to as many, or as few elements on each page as you want to without needing to update the code.

We hope you enjoyed this mini tutorial, and have fun applying the concept to your own site!

instagram icon     facebook icon     linkedin icon

© ODE DESIGN 2018. ALL RIGHTS RESERVED.

instagram icon     facebook icon     linkedin icon

© ODE DESIGN 2018. ALL RIGHTS RESERVED.