Change Theme using jQuery Split Button

by Vincy. Last modified on July 6th, 2023.

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.

View Demo

HTML Code for Split Button

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.

change-theme-using-jquery-split-button

<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>

Change Split Button Theme

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>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page