In this post, we will see how to change the theme color using jQuery. We have an example with a split button having two parts. One is for the default theme, and the other is to browse more themes.
In this example, we have three themes, Mercury, Sky, and 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 parts. The first one is to apply the default theme. And the button 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 shows a list of themes. Selecting themes 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>