How to create a light and dark mode switch for your site

How to create a light and dark mode switch for your site

Published Date
October 1, 2021
Tags
Design Tips
Author
Yusuf

Introduction

In this post, we will learn how to create keyboard shortcuts that will operate as a light/dark mode switch for your Notion-Super site. This post is for Notion-Super users, but is theoretically applicable to any kind of website.

Note that this method only works on desktop, where visitors have access to their keyboard. We'll learn how to create a visible switch that works on both desktop and mobile in a future post.

If you'd like to try a live demo, visit this site on desktop, yusuf.is/who and press 'L' and 'D' on your keyboard.

Step 1

CSS script

Head over to the code section of your site on Super. This could be the global site code or the individual page code, depending on where you want the theme switch to be.

Select your situation,

  • If you do not have your own light and dark themes CSS code yet, you can simply copy the code below and paste it to the CSS code section of your site.
  • Code
  • If you already have your own custom light and dark themes CSS code, I'll explain how to integrate it.
  • Explanation
  • If you already have a custom CSS code, but you do not have any light or dark theme CSS code, copy the code below and paste it at the top of your CSS code.
  • Code

Remember to click 'Save' once you're done.

Step 2

JavaScript code

Next, we'll create the keyboard shortcuts that will act as the theme switcher. To do this, we will need to write (read copy and paste) some code.

Copy the code below to the head section of your site, and click 'Save'. That's it.

<script>
	/* Change Theme */
	document.addEventListener("keydown", function(event) {
	  if (event.key === "d") {
	    document.documentElement.setAttribute('data-theme', 'dark');
	        localStorage.setItem('theme', 'dark');
	  }
	});
	document.addEventListener("keydown", function(event) {
	  if (event.key === "l") {
	    document.documentElement.setAttribute('data-theme', 'light');
	        localStorage.setItem('theme', 'light');
	  }
	});
</script>

Give it a test on your live site.

Pretty cool, huh?

Follow me on Twitter for more Notion-Super design hacks and tips.

Consider tipping me if you found this content useful.

Thanks, and take care.

— End

← Back

image