In this tutorial, we will go over a very useful feature in jQuery that will allow you to switch CSS stylesheets using only a few lines of code. The idea is very simple. If the user does not like the website’s color scheme, they can simply click a button or link and jQuery will change the look of the site by replacing the code line that links to the CSS.

Our Setup

Let’s start by setting up our project. You will first need to download and link to a copy of the jQuery core files as well as set up some the html. Here is an example of the markup we will be working with.

After you have setup the HTML. you will also need to create four CSS stylesheets named default.css, red.css, green.css and blue.css. This is very important as these are the names we will use to help setup the jQuery code and make the proper call when switching stylesheets. The Default.css is the main style we will start with and switch from there.

The jQuery

Next, we will go over setting up the jQuery code. To sum up the process we will ready the document and create four individual functions. One for each link that will perform the stylesheet switched when clicked. Place the following code between the reserved <script> tags. Let’s setup and review our code.

Each of the four functions will perform the same action. The only difference is the ID it is targeting and the stylesheet it will switch too. The first line will look for the given ID and will perform a function once that ID is clicked. Inside the function, it will look for the link tag with the rel=stylesheet, target the attribute (which is the href link in this case) and change it to link to a different stylesheet. Very short and simple.

Wrapping It Up

Using jQuery to switch out stylesheets can be a very useful feature for your website. A great example and one that is commonly used is to accommodate users who may be visually impaired and can click a button to switch stylesheets for a more legible website. There are many more uses and reasons why you may want to dynamically switch you stylesheets but also keep the User experience in mind when doing so.