I'm using bootstrap for the interface of the website I'm developing. I am also planning to integrate the bootswatch themes to my site. I have created a dropdown menu containing the different themes of bootswatch. My problem is how can I switch themes when I click one of the themes in the dropdown menu?
Fiddle:http://jsfiddle.net/82AsF/ (click the themes dropdown in the navbar)
Give your links a class theme-link
and a data-theme
value of the theme name like so:
<a href="#" data-theme="amelia" class="theme-link">Amelia</a>
Then, define your themes in a global variable like so:
var themes = {
"default": "//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css",
"amelia" : "//bootswatch.com/amelia/bootstrap.min.css",
"cerulean" : "//bootswatch.com/cerulean/bootstrap.min.css",
"cosmo" : "//bootswatch.com/cosmo/bootstrap.min.css",
"cyborg" : "//bootswatch.com/cyborg/bootstrap.min.css",
"flatly" : "//bootswatch.com/flatly/bootstrap.min.css",
"journal" : "//bootswatch.com/journal/bootstrap.min.css",
"readable" : "//bootswatch.com/readable/bootstrap.min.css",
"simplex" : "//bootswatch.com/simplex/bootstrap.min.css",
"slate" : "//bootswatch.com/slate/bootstrap.min.css",
"spacelab" : "//bootswatch.com/spacelab/bootstrap.min.css",
"united" : "//bootswatch.com/united/bootstrap.min.css"
}
(please host these bootswatch css files on your own server when you do this - I'm only hotlinking because I don't have a server on hand)
Then, use the following jQuery code:
$(function(){
var themesheet = $('<link href="'+themes['default']+'" rel="stylesheet" />');
themesheet.appendTo('head');
$('.theme-link').click(function(){
var themeurl = themes[$(this).attr('data-theme')];
themesheet.attr('href',themeurl);
});
});