Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make changeable themes using CSS and JavaScript

I'm pretty new to CSS and JavaScript and I was wondering if you could make a script that allows you to change what stylesheet the site uses.

Say: you had a green theme where everything is shades of green. What would you do so the user can change it to red with the press of a button?

Has anyone any idea how to do this?

like image 955
user1130772 Avatar asked Jan 09 '12 22:01

user1130772


People also ask

Can you modify CSS with JavaScript?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.


1 Answers

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 = '../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>
like image 110
Selvakumar Arumugam Avatar answered Sep 22 '22 23:09

Selvakumar Arumugam