In this post, we are going to see how to change theme color using jQuery. We have an example with a split button having two parts. One is for default theme and the other is to browse more themes.
In this example, we have three themes Mercury, Sky, Gold and separate CSS files for these themes. We are switching CSS files based on the selected theme. Then it will reflect on the split button and its dropdown UI.
This HTML code will show the split button with two part. first one is to apply default theme. And the more button is to show a list of available themes in a sub menu.
<div>
<a class="theme-color" id="default-theme">Default Theme</a><a id="theme-button">More...</a>
<ul id="theme-menu">
<li class="theme-color" id="mercury-theme">Mercury</li>
<li class="theme-color" id="sky-theme">Sky</li>
<li class="theme-color" id="gold-theme">Golden</li>
</ul>
</div>
This jQuery script is used to handle the split button click event. On clicking “Default Theme” the default-theme.css will be applied. And the “More” button, it shows a list of themes. On selecting themes it will change the button styles by loading the corresponding stylesheet.
<script>
$(function() {
$( "#theme-button" ).click(function() {
$("#theme-menu").show();
$( document ).on( "click", function() {
$("#theme-menu").hide();
});
$( ".theme-color" ).on( "click", function() {
var id = $(this).attr("id");
$("#theme-style").attr("href",id+".css");
});
return false;
})
});
</script>