Jul. 21st, 2024
2024年 6月 16日

Post: The Theme Toggler

The Theme Toggler

Published 12:05 May 18, 2020.

Created by @ezra. Categorized in #Programming.

Source format: Markdown

Table of Content

So, I am trying to add in a very simple method of switching between 2 stylesheets/themes.

Switch Theme by Changing Classes

Say we have this:

<body class="dark">
  <button id="theme-toggle" title="I'm a tooltip!">Switch</button>
  <div class="sq">Foo</div>

and this:

body {
  background-color: #F7F7F7;

body.dark .sq {
  border: 1px solid #000;
  background: #ffd43b;

body.light .sq {
  background-color: #fff;
  border: 2px dotted #000;

.sq {
  margin: 10px 0 0;
  height: 200px;

Save Status

now add JQuery:

<script src=""></script>

toggle and save:

function toggleTheme() {
  if($('body').hasClass('dark')) {
  } else {

$('#theme-toggle').click(function() {

Load Status

function loadTheme() {
  var themeSet = localStorage.getItem('theme');
  if (themeSet == 'dark') {
  } else {
<body class="dark">
  <!-- ... -->
  <!-- ... -->

localStorage Between Pages from Different Sites

But, do note that the localStorage isn't per page, it's by domain. That means and aren't considered as the same domain.

Best trick I know is to use iframes and postMessage API do get access to localStorage from external domain.

This technique is quite simple:

  • on you page you must create iframe to a domain from which you want to get data
  • your data domain need listen to message event: document.addEventListener ("message", handler, useCapture);
  • handler will be responsible for accessing localStorage and posting its content to source domain
  • your source domain may call handler function on data domain with postMessage API

For security of your data you can use HTTP header X-Frame-Options ALLOW-FROM uri

Switch Different Stylesheets

<script src=""></script>
<link rel="stylesheet" href="http://localhost:8888/demo/assets/themes/css/style1.css" type="text/css" media="all">

<button id="theme-toggle" title="I'm a tooltip!">Switch</button>
var defaultSS = '/assets/themes/css/style1.css',
    altSS = '/assets/themes/css/style2.css',

$('#theme-toggle').click(function () {

    hrefAttr = $(this).attr('href');
    if (hrefAttr.indexOf(defaultSS) >= 0) {
      $(this).attr('href', altSS);


    } else if (hrefAttr.indexOf(altSS) >= 0) {
      $(this).attr('href', defaultSS);

Pinned Message
I'm looking for a SOFTWARE PROJECT DIRECTOR / SOFTWARE R&D DIRECTOR position in a fresh and dynamic company. I would like to gain the right experience and extend my skills while working in great teams and big projects.
Feel free to contact me.
For more information, please view online résumé or download PDF
本人正在寻求任职 软件项目经理 / 软件技术经理 岗位的机会, 希望加⼊某个新鲜⽽充满活⼒的公司。
如有意向请随时 与我联系
更多信息请 查阅在线简历下载 PDF