Implementing random body classes with JavaScript

Ever want to have a random style applied on every page load? It could be a random color scheme, a background image, or anything else you can imagine.

We can accomplish this with a tiny snippet of JavaScript that adds a body class containing a random number from 1 to x (your choice of a maximum). Those potential body classes correspond with pre-defined CSS code that styles each one.

And because we’re generating the random number on the client-side with JavaScript, we’re “immune” to issues from page caching solutions.

If we tried to add a random body class with PHP (a server-side language) on a cached page, the applied styles would persist until the page cache was cleared, defeating the purpose of this technique.

And because we’re using a body class, we have flexibility to style whatever we want on the page, because we’re cascading as high as possible.

The use case we’ll cover in this tutorial will illustrate how to have a different header background image display on each page load. Specifically, we’ll be extending our page-specific header image tutorial to use random header images instead.

Let’s dig in!

The JavaScript

Let’s go ahead and just give you the JavaScript you’re going to need.

As explained in the code comments, feel free to change the “10” to the total number of random styles you want. Also, feel free to change “header-image-” to something else, especially if your use case has nothing to do with header images.

If you’re using Genesis, paste this in the “Footer Scripts” section of your theme settings page, <script> tags and all.

At this point, every time you refresh the page, a randomly selected body class will be output.

It could be .header-image-1, .header-image-2, .header-image-3, and so on up until .header-image-10. Making sense yet?

Keep in mind it is possible for the same body class to be added two page loads in a row, so don’t freak out if you see the same one on consecutive page loads, especially if you’ve decreased your total number from 10.

Now we need to write the corresponding CSS.

The CSS

As a refresher, we used the following CSS for styling a specific page with a custom header image in Beautiful Pro.

We’ll use a similar format for our random header image body classes.

And that’s all there is to it.

Leave a Reply

Your email address will not be published. Required fields are marked *