Using CSS and JavaScript to Randomize Background Images

I was working on a website and wanted to add a fun bit of flair by having the background rotate through a batch of images. So every time the website loaded it would have a different image. I did a little research, but none of the solutions were all that great. So I coded up my solution. I needed to be able to:

  • Randomize the images on page load
  • Set the random image on the body
  • Set the image on a pseudo-element ::backdrop

Solution 1 – JS sets the style

This was the first solution I ran across. I merged the original problem, with the solution to save time. What I dislike about this solution is the separation of concerns, and it uses “var” still.

<head>
<style>...</style>
<script type="text/javascript">
        var totalCount = 8;
        function ChangeIt() {
            var num = Math.ceil(Math.random() * totalCount);
            document.body.style.background = "url('assets/bgImages/" + num + ".jpg') repeat";

        }
    </script>
</head>
<body>...</body>

</html>
<script type="text/javascript">
    ChangeIt();
</script>

Stackoverflow solution 1

Solution 2 – JS inserts a stylesheet

This was the second solution I ran across. I started looking for this because I needed to add the random background to a pseudo-element – “::backdrop” for a dialog I was working on. Because you can’t directly access this pseudo-object from JS (at least I couldn’t see how) I tried to insert the stylesheet method. It was messy, and now I had two functions doing the “same thing”.

document.styleSheets[0].insertRule('#elid:hover { background-color: red; }', 0);
document.styleSheets[0].cssRules[0].style.backgroundColor= 'red';

//IE solution...
document.styleSheets[0].addRule('#elid:hover', 'background-color: red', 0);
document.styleSheets[0].rules[0].style.backgroundColor= 'red';

Stackoverflow Solution 2https://stackoverflow.com/a/311437

One commenter pointed out security issues, and I hated how messy this was. SO MUCH CSS in JS… ?

My solution – Set a class

To keep the CSS and styling out of the JS, don’t cross the streams, I let JS change the classes and left the styling in CSS.

This was a more elegant solution and allowed me to never edit the JS code if I wanted to switch images. This is a complete example with some “fixer” js to clear the classes off for the demo. Click around and have some fun.

  • Random <body> background-image
  • Random <div> background-image
  • Random <dialog> ::backdrop background-image

With this code and some css animations, you can create some really fun effects for your site.

See the Pen Random Background via class by Joel Cory (@Joel-Cory) on CodePen.