The latest web design trends have taken the web far more than expected. Much of the credit goes to the images, that adds a weight to content and describe it more naturally. These trends include manipulating the images to produce eye-popping visuals, for an example, using the Parallax scrolling effect. A random background that closely describes the content would also look alluring.

 

Randomizing the background

First of all, we have to select the background images. You can use some solid colors or images. You can even apply some funky gradients, up to you. But don’t generate the combination of them, it would look odd. So let’s get started by specifying some backgrounds.

 

Let’s have following classes with some gradient background images.

.pattern-1 {
  background: linear-gradient(45deg, #333 50%, #299 0);
}

.pattern-2 {
  background: repeating-linear-gradient(45deg, #299, #299 1em, 
                transparent 0, transparent 2em), tomato;
}

.pattern-3 {
  background: radial-gradient(circle at center, #333, #333 50%, #299 0);
}

.pattern-4 {
  background: repeating-linear-gradient(rgba(95, 174, 174, 0.34), 
                rgba(95, 174, 174, 0.34) 1em, transparent 0, transparent 2em), 
                repeating-linear-gradient(to right, rgba(95, 174, 174, 0.34), 
                rgba(95, 174, 174, 0.34) 1em, transparent 0, transparent 2em);
}

 

Now in Javascript, we can group these background images to build an array of these classes.

var backgrounds = [
        "pattern-1", 
        "pattern-2", 
        "pattern-3", 
        "pattern-4" 
];

 

The ‘Random’ Fact

When you multiply the length of an array (or any kind of list) with Math.random() (a built-in javascript function which generates numbers between 0 & 1) and round the result, the final result you get after rounding is one of the indices of array items. So let’s use this fact.

var randomBg = Math.floor(Math.random() * backgrounds.length);
    document.body.classList.add(backgrounds[randomBg]);


The variable ‘randomBg‘ stores the random index. We use this random index to fetch random classes (pattern-1, pattern-2 and so on) to add to the body (document.body) each time the page is loaded.

 

Here is the final Javascript code

( function() {
   var backgrounds = ["pattern-1", "pattern-2",
     "pattern-3", "pattern-4"];

   var randomBg = Math.floor(Math.random() * backgrounds.length);
   document.body.classList.add(backgrounds[randomBg]);
});

 

 

Here’s a demo of the discussion, let the randomness begin.

 

Reload multiple times to visualise the random background loading.

Click here for the full-screen view.

 

Conclusion

Just a few lines of javascript code and a new random background every time you load the page. Though random background technique visually enhances the content, but it harms more than good. More the number of images, more time the page would take to load. Make sure you do it in a controlled way.

Share on Facebook Tweet on Twitter Post on Google+ Buffer