Bootstrap Theme Switcher

While creating a Proof of Concept design for a website I was working on I thought it would be cool to demonstrate the power of themes in Twitter Bootstrap by providing an option in the Proof of Concept to switch to some of the themes that are on Bootswatch.  It was a remarkably easy solution, that involved jQuery, jQuery.cookie plugin, Twitter Bootstrap Navbar and the themes from Bootswatch.

This sample assumes that you are using a CDN for the Twitter Bootstrap and jQuery files and that you downloaded the themes from Bootswatch and copied them to the path of /css/themes. The example could easily be modified to use the themes on the Bootstrap CDN.

First, let’s start with a basic template for Twitter Bootstrap

Next, we’ll add the navbar to the theme selector menu.

Then, the JavaScript

Now you are done. But how does it work?

In the head section of the template, you should notice that one of the stylesheets an id of ‘bootstrapTheme‘. This link will be modified by the setTheme function in the JavaScript file to dynamically change the theme and save the theme preference to a cookie to load in the future. In the jQuery ready function, we check for the presence of the cookie ‘themeName‘, if present, a call is made to setTheme to load the theme. The theme is changed by clicking on one of theme menu items which, in turn, calls setTheme.

Leave a Reply