Simple Bootstrap Bootswatch style changer based on jQuery
This example shows how to implement client-side stylesheet changer, based on Twitter Bootstrap framework, Bootswatch styles for Bootstrap and jQuery. I used cssnewbie.com tutorial, with some own modifications.
This example is my modified answer to my own question at StackOverflow.
All you have to do, is to declare “default” stylesheet using title
attribute in <head>
section of your page:
<link href="assets/bootstrap/bootstrap.min.css" rel="stylesheet" media="screen" title="main"/>
Then add some links in form of list (can be used for building Bootstrap’s dropdown as well):
<ul class="dropdown-menu">
<li>
<a href="#" class="change-style-menu-item" rel="assets/bs/bootstrap.min.css">
<i class="icon-fixed-width icon-pencil"></i> bootstrap.min.css (Default)
</a>
</li>
<li>
<a href="#" class="change-style-menu-item" rel="assets/bs/bootstrap.cyborg.min.css">
<i class="icon-fixed-width icon-pencil"></i> bootstrap.cyborg.min.css (Cyborg)
</a>
</li>
</ul>
with rel
attribute pointing with full path to additional stylesheet.
You can of course add ass many stylesheets as you want, only make sure that you’re providing correct full path to each of them.
Finally, add a very simple jQuery function:
<script type="text/javascript">
/*< ![CDATA[*/
jQuery(function($)
{
$('body').on('click', '.change-style-menu-item', function()
{
$('link[title="main"]').attr('href', $(this).attr('rel'));
});
});
/*]]>*/
</script>
Works like a charm.
If you have only one stylesheet in entire page, you can omit adding title
attribute to link
tag and “catch” it using simple $('link')
selector instead of $('link[title="main"]')
.
Since I had other stylesheets included (bootstrap-responsive.min.css
), referencing “changeable” stylesheet with title
attribute was obligatory.