How to make changeable themes using CSS and JavaScript

You can set an Id to the link tag and switch the css at runtime.

HTML

<link type="text/css" rel="stylesheet" media="all" href="../green.css" id="theme_css" />

JS

document.getElementById('buttonID').onclick = function () { 
    document.getElementById('theme_css').href="https://stackoverflow.com/questions/8796107/red.css";
};

Quick Demo:

    $( "#datepicker" ).datepicker();

$('button').button().on('click', function () {
  let linkHref="https://code.jquery.com/ui/1.11.4/themes/{THEME}/jquery-ui.css";

if ($('#swapTheme').prop('href').indexOf('pepper-grinder') >= 0) {
    $('#swapTheme').prop('href', linkHref.replace('{THEME}', 'black-tie'));
  } else {
    $('#swapTheme').prop('href', linkHref.replace('{THEME}', 'pepper-grinder'));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
              crossorigin="anonymous"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/pepper-grinder/jquery-ui.css" id="swapTheme" rel="stylesheet">
<div id="datepicker"></div>
<button style="padding: 5px 15px;"> Switch Theme </button>

Leave a Comment