Skip to content

CoderLearningCode/drkmd.js

Repository files navigation

logo

drkmd.js

Build GitHub npm npm bundle size

Simple dark-mode/light-mode logic for any website

NPM

🔮 Live Demo

⚡ Features

  • Easy to integrate with any site (via script tag or NPM)
  • Specify different styles for the dark and light mode with CSS classes
  • Automatically detect system theme
  • Attach customizable theme toggle button to the page (or use it programmatically)
  • Store users choice in local storage or optionally as a cookie
  • Emits a theme-change event for advanced use cases like changing images

👋 Introduction

drkmd.js (short for darkmode.js) lets you add a dark-mode/light-mode toggle to any website. The library detects the system theme automatically and even saves the users choice in local storage or as a cookie.

The library will add the class theme-dark/theme-light to the body of the page and set the attribute data-theme to dark/light on the html tag which can be used to specify different css styles depending on the theme. You can also listen to a theme-change event for more advanced use cases. See usage below how you can customize your page with this.

🚀 Get started

Script tag

Add this to your HTML page:

<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js" data-drkmd></script>

With data-drkmd the button will be attached automatically on load, leave it out if you want to attach it manually

NPM

Install drkmd.js using NPM

npm install drkmd-js

Then add the following JavaScript code:

import Darkmode from 'drkmd-js';

new Darkmode().attach();

By default drkmd.js will add the button to the bottom right corner and save the users choice in local storage, this can be configured using the options.

📚 Usage

There are multiple ways to specify the different styles for the dark and light mode when using drkmd.js.

drkmd.js adds the class theme-dark/theme-light to the body element of your page, which can be used to specify different styles for each theme:

/* Styles for light theme */
.theme-light {
    background: #fff;
}

/* Styles for dark theme */
.theme-dark {
    background: #000;
}

The easiest way is to specify different colors for each theme using css variables:

/* Light Colors */
.theme-light {
    --background: #fff;
    --color: #000;
}

/* Dark Colors */
.theme-dark {
    --background: #000;
    --color: #fff;
}

html,
body {
    background: var(--background);
    color: var(--color);
}

drkmd.js also adds the attribute data-theme with either light or dark as the value to the html tag. With this the different themes can also be specified with the css selector [data-theme="dark"] and [data-theme="dark"].

Events

By default drkmd.js emits a theme-change event everytime the theme changes:

import Darkmode from 'drkmd-js';

new Darkmode();

window.addEventListener('theme-change', e => {
    console.log(e.detail.to); // will return 'light' or 'dark'
});

The theme-change event could be used to change the src attribute of an <img> tag depending on the theme (more info) or modify the page in any other way with JavaScript when the theme changes.

Programmatic Usage

drkmd.js can also be used programmatically if you don't want to show the button automatically on load or for other more advanced use cases.

To enable/disable Darkmode you can use the method toggle():

const darkmode = new Darkmode();
darkmode.toggle();

There are also other methods available:

darkmode.attach() // Attach the default darkmode button to the page
darkmode.toggle() // Toggle the theme
darkmode.isActivated() // Returns true if the darkmode is active
darkmode.toLight() // Change theme to light
darkmode.toDark() // Change theme to dark

⚙️ Options

You can customize drkmd.js in two different ways, depending on how you are including it in your site.

The main method is to pass a options object to new Darkmode():

const options = {
  top: '20px', // default: 'unset'
  bottom: 'unset', // default: '20px'
  right: 'unset', // default: '20px'
  left: '32px', // default: 'unset'
  buttonLight: '#fff',  // default: '#fff'
  buttonDark: '#000', // default: '#000'
  events: false, // default: true
  cookie: true, // default: false
  localStorage: false, // default: true (will take precedence over cookie)
  label: '', // default: '🌓'
  autoMatchOsTheme: false, // default: true
  defaultTheme: 'dark', // default: 'light'
}

const darkmode = new Darkmode(options);
darkmode.attach();

The other method is to specify the options as the value for the data-drkmd attribute:

<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js" data-drkmd='{ "defaultTheme": "dark", "cookie": true }'></script>

This works on any element, but it is recommended to only use it when you are loading drkmd via the script tag.

📖 Examples

All examples below use drkmd-js by loading it via a CDN in a script tag (more info in the get started section):

HTML

<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js" data-drkmd></script>

Basic

Render the darkmode toggle with all the default options:

JavaScript

new Darkmode().attach()

Specify different colors for each theme with CSS variables:

CSS

[data-theme="light"] {
    --background: #fff;
    --color: #000;
}

[data-theme="dark"] {
    --background: #000;
    --color: #fff;
}

html,
body {
    background: var(--background);
    color: var(--color);
}

With options

Render the darkmode toggle with custom options:

JavaScript

const options = {
  right: 'unset',
  left: '32px',
  defaultTheme: 'dark',
}

new Darkmode(options).attach()

Custom darkmode toggle

Don't render the darkmode toggle, instead change the theme on a button press:

HTML

<button id="myBtn">Change theme</button>

JavaScript

const darkmode = new Darkmode()

document.getElementById('myBtn').addEventListener('click', function() {
    darkmode.toggle()
})

Different images depending on the theme

You can use the theme-change event to modify an element with JavaScript. Here we are changing the src attribute of an img tag when the theme changes:

HTML

<img id="image" src="/path/to/dark.png">

JavaScript

new Darkmode().attach()

const imageSrc = {
   dark: "/path/to/dark.png",
   light: "/path/to/light.png"
}

window.addEventListener('theme-change', e => {
    const theme = e.detail.to // will return 'light' or 'dark'
    document.getElementById('image').src = imageSrc[theme]
})

Different styles depending on the theme

You can use the classes theme-dark and theme-light to use different styles depending on the theme:

JavaScript

new Darkmode().attach()

CSS

.theme-dark {
    /* Styles for dark theme */
}

.theme-light {
    /* Styles for light theme */
}

Note: The classes will be added to the body of your HTML page.

🌍 Browser compatibility

drkmd.js uses prefers-color-scheme: dark to automatically enable the Dark Mode if the OS prefered theme is dark.

Check the current compatibility here:

💻 Development

Issues and PRs are very welcome!

The actual source code of this library is in the drkmd.js file in the src folder.

Run yarn build or npm run build to produce a production version of drkmd.js in the dist folder.

❔ About

This library was developed by me (@betahuhn) in my free time. If you want to support me:

Donate via PayPal

Credits

The library was inspired by Darkmode.js which is similar, but uses a different approach by directly changing the background color of your page, instead of letting you customize everything via css variables.

License

Copyright 2021 Maximilian Schiller

This project is licensed under the MIT License - see the LICENSE file for details

About

🌓 Simple dark-mode/light-mode logic for any website.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 87.5%
  • HTML 12.5%