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!

To read the rest of this tutorial, you will need a Pro account.

Request tutorials, download exclusive themes, and post on our community forums with a free membership.

Join for free

Error: Please enter a valid email address

Error: Invalid email

Error: Please enter your first name

Error: Please enter your last name

Error: Please enter a username

Error: Please enter a password

Error: Please confirm your password

Error: Password and password confirmation do not match