Bootstrap Theme Switcher

2 minute read

UPDATE: This is now a jQuery Plugin. See the post Bootstrap Theme Switcher jQuery Plugin. While creating a Proof of Concept design for a web site 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

<html lang="en">
        <!-- Bootstrap core CSS -->
        <link rel="stylesheet"
        <link rel="stylesheet"
        <link id="bootstrapTheme" rel="stylesheet"
        <link rel="stylesheet"
        <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->   
        <script src=""></script>
        <script src=""></script>

<div class="container-fluid">

Your content here!


<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src=""
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src=""
<script src="/js/site.js" type="text/javascript"></script>


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

<div class="container">
  <div class="navbar-header">
    <button class="navbar-toggle"> 
      <span class="sr-only">Toggle navigation</span>
      <a class="navbar-brand" href="index.html">Intro to Twitter Bootstrap</a>
  <div class="collapse navbar-collapse">
  <ul class="nav navbar-nav">
    <li class="dropdown"><a class="dropdown-toggle" href="#">Bootstrap Site </a>
      <ul class="dropdown-menu">
  </div><!--/.nav-collapse -->

Then, the JavaScript

$().ready(function() {
  /* For theme switching */
  var themeName = $.cookie("themeName");
  var themePath = $.cookie("themePath");
  if (themeName !== undefined) {
    setTheme(themeName, themePath);

function setTheme(themeName, themePath) {
  var cssLink = "";

  $.cookie("themeName", themeName, { expires: 7, path: "/" });
  $.cookie("themePath", themePath, { expires: 7, path: "/" });

Now you are done. But how does it work? In the head section of the template you should notice that we gave 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.