Comparing version 0.2.18 to 1.0.0
@@ -0,1 +1,24 @@ | ||
## [v1.0.0] - 2021-04-07 | ||
[Release notes](https://github.com/BetaHuhn/drkmd.js/releases/tag/v1.0.0) · [Compare](https://github.com/BetaHuhn/drkmd.js/compare/v0.2.18...v1.0.0) · [Tag](https://github.com/BetaHuhn/drkmd.js/tree/v1.0.0) · Archive ([zip](https://github.com/BetaHuhn/drkmd.js/archive/v1.0.0.zip) · [tar.gz](https://github.com/BetaHuhn/drkmd.js/archive/v1.0.0.tar.gz)) | ||
### New features | ||
- [`ef0ffc3`](https://github.com/BetaHuhn/drkmd.js/commit/ef0ffc3) Detect data attributes | ||
- [`f305a03`](https://github.com/BetaHuhn/drkmd.js/commit/f305a03) Use attribute to change theme on click | ||
### Updates | ||
- [`df25c9d`](https://github.com/BetaHuhn/drkmd.js/commit/df25c9d) Cleanup code | ||
- [`e8cfd72`](https://github.com/BetaHuhn/drkmd.js/commit/e8cfd72) Add more comments, reduce complexity | ||
### Dependency updates | ||
- [`9b7e344`](https://github.com/BetaHuhn/drkmd.js/commit/9b7e344) Update dependencies | ||
### Breaking changes | ||
- [`b42e1fd`](https://github.com/BetaHuhn/drkmd.js/commit/b42e1fd) ♻️ Prepend internal function with _ | ||
- [`4ebce82`](https://github.com/BetaHuhn/drkmd.js/commit/4ebce82) Remove isActivated method (replaced with isDark/isLight) | ||
## [v0.2.18] - 2021-04-05 | ||
@@ -2,0 +25,0 @@ |
@@ -1,1 +0,1 @@ | ||
!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).drkmdJs=t()}}((function(){return function t(e,o,n){function r(a,s){if(!o[a]){if(!e[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(i)return i(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var d=o[a]={exports:{}};e[a][0].call(d.exports,(function(t){return r(e[a][1][t]||t)}),d,d.exports,t,e,o,n)}return o[a].exports}for(var i="function"==typeof require&&require,a=0;a<n.length;a++)r(n[a]);return r}({1:[function(t,e,o){"use strict";function n(t,e){for(var o=0;o<e.length;o++){var n=e[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}Object.defineProperty(o,"__esModule",{value:!0}),o.default=o.IS_BROWSER=void 0;var r="undefined"!=typeof window;o.IS_BROWSER=r;var i=function(){function t(e){var o=this;if(function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),r){e=Object.assign({},{top:"unset",bottom:"20px",right:"20px",left:"unset",buttonLight:"#fff",buttonDark:"#000",events:!0,cookie:!1,localStorage:!0,label:"🌓",autoMatchOsTheme:!0,defaultTheme:"light"},e),this.options=e,this.dark=!1,e.autoMatchOsTheme&&(window.matchMedia("(prefers-color-scheme: dark)").addListener((function(t){return t.matches&&o.switchThemePrefers()})),window.matchMedia("(prefers-color-scheme: light)").addListener((function(t){return t.matches&&o.switchThemePrefers()})));var n=this.getStorageValue();null!==n?"true"===n||!0===n?this.toDark():this.toLight():e.autoMatchOsTheme?this.preferedTheme()?this.toDark():this.toLight():"light"===e.defaultTheme?this.toLight():this.toDark()}else console.warn("Detected environment without a `window` object")}var e,o,i;return e=t,(o=[{key:"attach",value:function(){var t=this,e="\n .drkmd-toggle-button{\n position: fixed;\n z-index: 1000;\n left: ".concat(this.options.left,";\n right: ").concat(this.options.right,";\n bottom: ").concat(this.options.bottom,";\n top: ").concat(this.options.top,";\n height: 3rem;\n min-width: 3rem;\n border-radius: 3rem;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ").concat(this.options.buttonDark,";\n color: ").concat(this.options.buttonLight,";\n cursor: pointer;\n }\n\n .drkmd-toggle-button span{\n margin: 0;\n padding: 0px 10px;\n }\n\n .theme-dark .drkmd-toggle-button{\n background: ").concat(this.options.buttonLight,";\n color: ").concat(this.options.buttonDark,"\n }\n "),o=document.createElement("div"),n=document.createElement("span");n.innerHTML=this.options.label,o.className="drkmd-toggle-button",o.setAttribute("title","Toggle dark mode"),o.setAttribute("aria-label","Toggle dark mode"),o.setAttribute("aria-checked","false"),o.setAttribute("role","checkbox"),o.appendChild(n),o.addEventListener("click",(function(){!0===t.dark?t.toLight():t.toDark()})),document.body.insertBefore(o,document.body.firstChild),this.addStyle(e)}},{key:"toLight",value:function(){this.options.events&&window.dispatchEvent(new CustomEvent("theme-change",{detail:{to:"light"}})),document.documentElement.setAttribute("data-theme","light"),this.setStorageValue(!1),document.body.classList.remove("theme-dark"),document.body.classList.add("theme-light"),this.dark=!1}},{key:"toDark",value:function(){this.options.events&&window.dispatchEvent(new CustomEvent("theme-change",{detail:{to:"dark"}})),document.documentElement.setAttribute("data-theme","dark"),this.setStorageValue(!0),document.body.classList.add("theme-dark"),document.body.classList.remove("theme-light"),this.dark=!0}},{key:"preferedTheme",value:function(){return window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches}},{key:"switchThemePrefers",value:function(){!0===this.preferedTheme()?this.swichToDark():this.swichToLight()}},{key:"getStorageValue",value:function(){if(this.options.localStorage&&null!==window.localStorage)return window.localStorage.getItem("darkmode");if(this.options.cookie){var t=document.cookie.match(RegExp("(?:^|;\\s*)darkmode=([^;]*)"));return t?t[1]:null}return null}},{key:"setStorageValue",value:function(t){this.options.localStorage&&null!==window.localStorage?window.localStorage.setItem("darkmode",t):this.options.cookie&&(document.cookie="darkmode=".concat(t))}},{key:"toggle",value:function(){return this.dark?this.toLight():this.toDark(),this.dark}},{key:"isActivated",value:function(){return this.dark}},{key:"addStyle",value:function(t){var e=document.createElement("link");e.setAttribute("rel","stylesheet"),e.setAttribute("type","text/css"),e.setAttribute("href","data:text/css;charset=UTF-8,"+encodeURIComponent(t)),document.head.appendChild(e)}}])&&n(e.prototype,o),i&&n(e,i),t}();o.default=i},{}],2:[function(t,e,o){"use strict";function n(t){return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}Object.defineProperty(o,"__esModule",{value:!0}),o.default=void 0;var r=function(t){if(t&&t.__esModule)return t;if(null===t||"object"!==n(t)&&"function"!=typeof t)return{default:t};var e=i();if(e&&e.has(t))return e.get(t);var o={},r=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var a in t)if(Object.prototype.hasOwnProperty.call(t,a)){var s=r?Object.getOwnPropertyDescriptor(t,a):null;s&&(s.get||s.set)?Object.defineProperty(o,a,s):o[a]=t[a]}o.default=t,e&&e.set(t,o);return o}(t("./drkmd"));function i(){if("function"!=typeof WeakMap)return null;var t=new WeakMap;return i=function(){return t},t}var a=r.default;o.default=a,r.IS_BROWSER&&function(t){t.Darkmode=r.default}(window)},{"./drkmd":1}]},{},[2])(2)})); | ||
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).drkmdJs=e()}}((function(){return function e(t,n,o){function r(i,d){if(!n[i]){if(!t[i]){var c="function"==typeof require&&require;if(!d&&c)return c(i,!0);if(a)return a(i,!0);var u=new Error("Cannot find module '"+i+"'");throw u.code="MODULE_NOT_FOUND",u}var l=n[i]={exports:{}};t[i][0].call(l.exports,(function(e){return r(t[i][1][e]||e)}),l,l.exports,e,t,n,o)}return n[i].exports}for(var a="function"==typeof require&&require,i=0;i<o.length;i++)r(o[i]);return r}({1:[function(e,t,n){"use strict";function o(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}Object.defineProperty(n,"__esModule",{value:!0}),n.default=n.IS_BROWSER=void 0;var r="undefined"!=typeof window;n.IS_BROWSER=r;var a=function(){function e(t){var n=this;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);t=Object.assign({},{top:"unset",bottom:"20px",right:"20px",left:"unset",attach:!1,buttonLight:"#fff",buttonDark:"#000",events:!0,cookie:!1,localStorage:!0,label:"🌓",autoMatchOsTheme:!0,defaultTheme:"light"},t),this.options=t,this.dark=!1,t.autoMatchOsTheme&&(window.matchMedia("(prefers-color-scheme: dark)").addListener((function(e){return e.matches&&n._handlePreferedThemeChangeEvent()})),window.matchMedia("(prefers-color-scheme: light)").addListener((function(e){return e.matches&&n._handlePreferedThemeChangeEvent()})));var o="light"!==t.defaultTheme;if(t.autoMatchOsTheme&&(o=this._preferedThemeIsDark()),this.options.cookie){var r=document.cookie.match(RegExp("(?:^|;\\s*)darkmode=([^;]*)"));o=r?"true"===r[1]:null}this.options.localStorage&&null!==window.localStorage&&(o="true"===window.localStorage.getItem("darkmode")),this._changeThemeToDark(o)}var t,n,r;return t=e,(n=[{key:"attach",value:function(){var e=this,t="\n .drkmd-toggle-button{\n position: fixed;\n z-index: 1000;\n left: ".concat(this.options.left,";\n right: ").concat(this.options.right,";\n bottom: ").concat(this.options.bottom,";\n top: ").concat(this.options.top,";\n height: 3rem;\n min-width: 3rem;\n border-radius: 3rem;\n display: flex;\n align-items: center;\n justify-content: center;\n background: ").concat(this.options.buttonDark,";\n color: ").concat(this.options.buttonLight,";\n cursor: pointer;\n }\n\n .drkmd-toggle-button span{\n margin: 0;\n padding: 0px 10px;\n }\n\n .theme-dark .drkmd-toggle-button{\n background: ").concat(this.options.buttonLight,";\n color: ").concat(this.options.buttonDark,"\n }\n "),n=document.createElement("div"),o=document.createElement("span");o.innerHTML=this.options.label,n.className="drkmd-toggle-button",n.setAttribute("title","Toggle dark mode"),n.setAttribute("aria-label","Toggle dark mode"),n.setAttribute("aria-checked","false"),n.setAttribute("role","checkbox"),n.appendChild(o),n.addEventListener("click",(function(){e.toggle()})),document.body.insertBefore(n,document.body.firstChild),this._addStyle(t)}},{key:"toLight",value:function(){this.options.events&&window.dispatchEvent(new CustomEvent("theme-change",{detail:{to:"light"}})),document.documentElement.setAttribute("data-theme","light"),document.body.classList.remove("theme-dark"),document.body.classList.add("theme-light"),this._setStorageValue(!1),this.dark=!1}},{key:"toDark",value:function(){this.options.events&&window.dispatchEvent(new CustomEvent("theme-change",{detail:{to:"dark"}})),document.documentElement.setAttribute("data-theme","dark"),document.body.classList.add("theme-dark"),document.body.classList.remove("theme-light"),this._setStorageValue(!0),this.dark=!0}},{key:"toggle",value:function(){var e=!this.dark;return this._changeThemeToDark(e),e}},{key:"isDark",value:function(){return!0===this.dark}},{key:"isLight",value:function(){return!1===this.dark}},{key:"currentTheme",value:function(){return this.dark?"dark":"light"}},{key:"_preferedThemeIsDark",value:function(){return window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches}},{key:"_handlePreferedThemeChangeEvent",value:function(){var e=this._preferedThemeIsDark();this._changeThemeToDark(e)}},{key:"_changeThemeToDark",value:function(e){e?this.toDark():this.toLight()}},{key:"_setStorageValue",value:function(e){this.options.localStorage&&null!==window.localStorage?window.localStorage.setItem("darkmode",e):this.options.cookie&&(document.cookie="darkmode=".concat(e))}},{key:"_addStyle",value:function(e){var t=document.createElement("link");t.setAttribute("rel","stylesheet"),t.setAttribute("type","text/css"),t.setAttribute("href","data:text/css;charset=UTF-8,"+encodeURIComponent(e)),document.head.appendChild(t)}}])&&o(t.prototype,n),r&&o(t,r),e}();n.default=a},{}],2:[function(e,t,n){"use strict";function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var r=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==o(e)&&"function"!=typeof e)return{default:e};var t=a();if(t&&t.has(e))return t.get(e);var n={},r=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e)if(Object.prototype.hasOwnProperty.call(e,i)){var d=r?Object.getOwnPropertyDescriptor(e,i):null;d&&(d.get||d.set)?Object.defineProperty(n,i,d):n[i]=e[i]}n.default=e,t&&t.set(e,n);return n}(e("./drkmd"));function a(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return a=function(){return e},e}var i=r.default;n.default=i;r.IS_BROWSER?function(){var e=document.querySelector("[data-drkmd-opts]"),t=document.querySelector("[data-drkmd-attach]"),n=document.querySelectorAll("[data-drkmd-toggle]"),o=document.querySelectorAll("[data-drkmd-to-light]"),a=document.querySelectorAll("[data-drkmd-to-dark]");if(!e&&!t&&n.length<1&&o.length<1&&a.length<1)window.Darkmode=r.default;else{var i=e&&e.getAttribute("data-drkmd-opts")||"{}",d=JSON.parse(i);if(window.darkmode=new r.default(d),n.length>0)for(var c=0;c<n.length;c++)n[c].addEventListener("click",(function(){window.darkmode.toggle()}));if(o.length>0)for(var u=0;u<o.length;u++)o[u].addEventListener("click",(function(){window.darkmode.toLight()}));if(a.length>0)for(var l=0;l<a.length;l++)a[l].addEventListener("click",(function(){window.darkmode.toDark()}));(window.darkmode.options.attach||t)&&window.darkmode.attach()}}():console.warn("drkmd.js: Detected environment without a `window` object")},{"./drkmd":1}]},{},[2])(2)})); |
{ | ||
"name": "drkmd-js", | ||
"version": "0.2.18", | ||
"version": "1.0.0", | ||
"description": "Simple dark-mode/light-mode toggle for any website", | ||
@@ -8,2 +8,3 @@ "main": "dist/drkmd-js.min.js", | ||
"lint": "eslint ./src/", | ||
"dev": "watch 'npm run build' ./src/ ./examples/ --interval=1", | ||
"build": "node build.js", | ||
@@ -31,4 +32,3 @@ "semantic-release": "semantic-release" | ||
"files": [ | ||
"dist", | ||
"src" | ||
"dist" | ||
], | ||
@@ -38,3 +38,4 @@ "devDependencies": { | ||
"eslint": "^7.16.0", | ||
"rosid-handler-js": "^13.0.2" | ||
"rosid-handler-js": "^13.0.2", | ||
"watch": "^1.0.2" | ||
}, | ||
@@ -41,0 +42,0 @@ "publishConfig": { |
325
README.md
@@ -18,2 +18,11 @@ <div align="center"> | ||
## ⚡ Features | ||
- Easy to integrate with any site (via [script tag](#script-tag) or [NPM](#npm)) | ||
- Specify different styles for the dark and light mode with [CSS classes](#styling) | ||
- Automatically detects system theme (and theme changes) | ||
- Trigger a them change with the [default theme toggle](#default-theme-toggle), a [custom element](#custom-buttons) or even [programmatically](#programmatic) | ||
- Stores users choice in local storage or [optionally](#%EF%B8%8F-options) as a cookie | ||
- Emits a `theme-change` [event](#events) for advanced use cases like [changing images](#different-images-depending-on-the-theme) | ||
## 👋 Introduction | ||
@@ -23,7 +32,7 @@ | ||
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. See [usage](https://github.com/BetaHuhn/drkmd.js#usage) below how you can customize your page with this. | ||
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](#-usage) below how you can customize your page with this. | ||
## 🚀 Get started | ||
### JSDelivr | ||
### Script tag | ||
@@ -33,9 +42,3 @@ Add this to your HTML page: | ||
```html | ||
<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js"></script> | ||
<script> | ||
function addDarkmode() { | ||
new Darkmode().attach(); | ||
} | ||
window.addEventListener('load', addDarkmode); | ||
</script> | ||
<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js" data-drkmd-attach></script> | ||
``` | ||
@@ -54,57 +57,76 @@ | ||
```javascript | ||
import Darkmode from 'drkmd-js'; | ||
import Darkmode from 'drkmd-js' | ||
new Darkmode().attach(); | ||
new Darkmode().attach() | ||
``` | ||
By default [drkmd.js](https://github.com/BetaHuhn/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](https://github.com/BetaHuhn/drkmd.js#options) object. | ||
Both methods will add the [darkmode toggle](#default-theme-toggle) with all the default [options](#%EF%B8%8F-options) to your page. | ||
The last step is to specify the [styling](#styling) for each theme and then you're done 🎉 | ||
Enjoy the dark side 🖤 | ||
## 📚 Usage | ||
You can either use the class `theme-dark`/`theme-light` to change your css depending on the theme, or set css variables to specify colors for each theme: | ||
### Styling | ||
There are multiple ways to specify the different styles for the dark and light mode when using [drkmd.js](https://github.com/BetaHuhn/drkmd.js). | ||
[drkmd.js](https://github.com/BetaHuhn/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: | ||
```css | ||
/* Light Colors */ | ||
[data-theme="light"] { | ||
--background: #fff; | ||
--color: #000; | ||
/* Styles for light theme */ | ||
.theme-light { | ||
background: #fff; | ||
} | ||
/* Dark Colors */ | ||
[data-theme="dark"] { | ||
--background: #000; | ||
--color: #fff; | ||
/* Styles for dark theme */ | ||
.theme-dark { | ||
background: #000; | ||
} | ||
``` | ||
html, | ||
body { | ||
background: var(--background); | ||
color: var(--color); | ||
} | ||
In most cases it is easier to specify [css-variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) for different themes (See [below](#css-variables) for an example). | ||
[drkmd.js](https://github.com/BetaHuhn/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"]`. | ||
### Default theme toggle | ||
The easiest way to change the theme is to use the included theme toggle by either adding the `data-drkmd-attach` attribute to the script tag (or any other element): | ||
```html | ||
<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js" data-drkmd-attach></script> | ||
``` | ||
### Events | ||
or by calling `.attach()`: | ||
By default [drkmd.js](https://github.com/BetaHuhn/drkmd.js) emits a `theme-change` event if the theme changes: | ||
```javascript | ||
new Darkmode().attach() | ||
``` | ||
```js | ||
import Darkmode from 'drkmd-js'; | ||
If you use any of the [options](#%EF%B8%8F-options) you can also set `attach: true` to achieve the same as the two methods above. | ||
new Darkmode(); | ||
By default the button will be added to the bottom right corner of the page and the users choice will be saved in local storage. This can be configured using the [options](#%EF%B8%8F-options). | ||
window.addEventListener('theme-change', e => { | ||
console.log(e.detail.to); // will return 'light' or 'dark' | ||
}); | ||
### Custom buttons | ||
You can add the attribute `data-drkmd-toggle` to any element to transform it into a theme toggle: | ||
```html | ||
<span data-drkmd-toggle>Toggle theme</span> | ||
``` | ||
The `theme-change` event could be used to change the `src` attribute of an `<img>` tag depending on the theme ([more info](https://github.com/BetaHuhn/drkmd.js/discussions/11#discussioncomment-247341)) or modify the page in any other way with JavaScript when the theme changes. | ||
When the element is clicked the current theme will be changed. | ||
## 🛠️ Manual Usage | ||
You can also use `data-drkmd-to-light` and `data-drkmd-to-dark` to switch to a specific theme. | ||
If you don't want to show the button and enable/disable Darkmode programatically you can use the method `toggle()`: | ||
### Programmatic | ||
[drkmd.js](https://github.com/BetaHuhn/drkmd.js) can also be used programmatically for more advanced use cases. | ||
To enable/disable Darkmode you can use the method `toggle()`: | ||
```javascript | ||
const darkmode = new Darkmode(); | ||
darkmode.toggle(); | ||
const darkmode = new Darkmode() | ||
darkmode.toggle() | ||
``` | ||
@@ -115,58 +137,118 @@ | ||
```js | ||
darkmode.attach() //Create default darkmode button | ||
darkmode.toggle() // Toggle theme | ||
darkmode.isActivated() // If darkmode is active | ||
darkmode.attach() // Attach the default darkmode button to the page | ||
darkmode.toggle() // Toggle the theme | ||
darkmode.toLight() // Change theme to light | ||
darkmode.toDark() // Change theme to dark | ||
darkmode.currentTheme() // Returns the current theme as a string (dark/light) | ||
darkmode.isDark() // Returns true if the current theme is dark | ||
darkmode.isLight() // Returns true if the current theme is light | ||
``` | ||
### Events | ||
By default [drkmd.js](https://github.com/BetaHuhn/drkmd.js) emits a `theme-change` event everytime the theme changes: | ||
```js | ||
import Darkmode from 'drkmd-js' | ||
new Darkmode() | ||
window.addEventListener('theme-change', e => { | ||
console.log(e.detail.to) // will return 'light' or 'dark' | ||
}) | ||
``` | ||
This can be turned off by setting the option `events: false`. | ||
The `theme-change` event could be used to change the `src` attribute of an `<img>` tag depending on the theme (example [below](#different-images-depending-on-the-theme)) or modify the page in any other way with JavaScript when the theme changes. | ||
## ⚙️ Options | ||
You can customize [drkmd.js](https://github.com/BetaHuhn/drkmd.js) by passing a options object to `new Darkmode()`: | ||
You can customize the behaviour of [drkmd.js](https://github.com/BetaHuhn/drkmd.js) and the style of the included toggle with these options: | ||
| Name | Description | Default | Example | | ||
| ------------- | ------------- | ------------- | ------------- | | ||
| `localStorage` | Store the users choice in the local storage | `true` | `false` | | ||
| `cookie` | Store the users choice in a cookie (local storage takes precedence) | `false` | `true` | | ||
| `events` | Emit the [`theme-change` event](#events) | `true` | `false` | | ||
| `autoMatchOsTheme` | Detect the system theme and automatically change to it | `true` | `false` | | ||
| `defaultTheme` | Specify which theme should be used on the first visit | `light` | `dark` | | ||
| `attach` | Specify if the default toggle should be attached (can be used instead of [`data-drkmd-attach`](#default-theme-toggle)) | `false` | `true` | | ||
| `label` | Specify a custom label for the theme toggle | `🌓` | `💡` | | ||
| `buttonLight` | Background color of the theme toggle for the light mode | `#fff` | `#222` | | ||
| `buttonDark` | Background color of the theme toggle for the dark mode | `#000` | `#222` | | ||
| `top` | Space in px from the toggle to the top of the page (if set toggle will be placed at the top) | `unset` | `20px` | | ||
| `bottom` | Space in px from the toggle to the bottom of the page (if set toggle will be placed at the bottom) | `20px` | `unset` | | ||
| `right` | Space in px from the toggle to the right edge of the page (if set toggle will be placed on the left side)| `unset` | `20px` | | ||
| `left` | Space in px from the toggle to the left edge of the page (if set toggle will be placed on the right side) | `20px` | `unset` | | ||
You can specify any number of them as the value for the `data-drkmd-opts` attribute (make sure the value is valid JSON): | ||
```html | ||
<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js" data-drkmd-opts='{ "defaultTheme": "dark", "cookie": true }'></script> | ||
``` | ||
> This works on any element, not just the script tag, so you can even use it when you are loading [drkmd.js](https://github.com/BetaHuhn/drkmd.js) via [NPM](#npm). | ||
or you can pass them as a JS object to `new Darkmode()`: | ||
```js | ||
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' | ||
cookie: true, | ||
defaultTheme: 'dark', | ||
} | ||
const darkmode = new Darkmode(options); | ||
darkmode.attach(); | ||
const darkmode = new Darkmode(options) | ||
``` | ||
## ⚡ Examples | ||
## 📖 Examples | ||
All examples below use `drkmd-js` by loading it via a CDN in a script tag (more info in the [get started](#-get-started) section): | ||
### Basic | ||
[View example file](https://github.com/BetaHuhn/drkmd.js/blob/master/examples/basic/index.html) | ||
Render the darkmode toggle with all the default options. | ||
Import [drkmd.js](https://github.com/BetaHuhn/drkmd.js) like this: | ||
**HTML** | ||
```html | ||
<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js"></script> | ||
<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js" data-drkmd-attach></script> | ||
``` | ||
--- | ||
or | ||
### Basic | ||
Render the darkmode toggle with all the default options: | ||
**JavaScript** | ||
```js | ||
import Darkmode from 'drkmd-js' | ||
new Darkmode().attach() | ||
``` | ||
Specify different colors for each theme with CSS variables: | ||
Then specify the styles for the light and dark theme: | ||
**CSS** | ||
```css | ||
[data-theme="light"] { | ||
/* Styles for light theme */ | ||
.theme-light { | ||
background: #fff; | ||
} | ||
/* Styles for dark theme */ | ||
.theme-dark { | ||
background: #000; | ||
} | ||
``` | ||
--- | ||
### CSS variables | ||
[View example file](https://github.com/BetaHuhn/drkmd.js/blob/master/examples/css-variables/index.html) | ||
If you want to specify different colors for each theme, you can use [css-variables](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties): | ||
**CSS** | ||
```css | ||
/* Light Colors */ | ||
.theme-light { | ||
--background: #fff; | ||
@@ -176,3 +258,4 @@ --color: #000; | ||
[data-theme="dark"] { | ||
/* Dark Colors */ | ||
.theme-dark { | ||
--background: #000; | ||
@@ -193,6 +276,17 @@ --color: #fff; | ||
[View example file](https://github.com/BetaHuhn/drkmd.js/blob/master/examples/options/index.html) | ||
Render the darkmode toggle with custom options: | ||
**HTML** | ||
```html | ||
<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js" data-drkmd-opts='{ "right": "unset", "left": "32px", "defaultTheme": "dark" }'></script> | ||
``` | ||
or | ||
**JavaScript** | ||
```js | ||
import Darkmode from 'drkmd-js' | ||
const options = { | ||
@@ -211,18 +305,32 @@ right: 'unset', | ||
Don't render the darkmode toggle, instead change the theme on a button press: | ||
[View example file](https://github.com/BetaHuhn/drkmd.js/blob/master/examples/custom-toggle/index.html) | ||
Don't render the darkmode toggle, instead change the theme when a custom HTML element is clicked. | ||
Import [drkmd.js](https://github.com/BetaHuhn/drkmd.js) like this: | ||
**HTML** | ||
```html | ||
<button id="myBtn">Change theme</button> | ||
<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js"></script> | ||
``` | ||
> Note: `data-drkmd-attach` is missing because we don't want to attach the default toggle to the page | ||
or | ||
**JavaScript** | ||
```js | ||
const darkmode = new Darkmode() | ||
import Darkmode from 'drkmd-js' | ||
``` | ||
document.getElementById('myBtn').addEventListener('click', function() { | ||
darkmode.toggle() | ||
}) | ||
Then on your custom element add the attribute `data-drkmd-toggle`: | ||
```html | ||
<span data-drkmd-toggle>Change theme</span> | ||
``` | ||
When you click that element, the theme will be toggled automatically. | ||
There's also `data-drkmd-to-light` and `data-drkmd-to-dark` which will change the theme to either dark or light specifically. | ||
--- | ||
@@ -232,4 +340,6 @@ | ||
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: | ||
[View example file](https://github.com/BetaHuhn/drkmd.js/blob/master/examples/events/index.html) | ||
You can use the `theme-change` [event](#events) to modify an element with JavaScript. Here we are changing the `src` attribute of an `img` tag when the theme changes: | ||
**HTML** | ||
@@ -242,3 +352,3 @@ ```html | ||
```js | ||
new Darkmode().attach() | ||
new Darkmode().attach() // or use the data-drkmd-attach attribute | ||
@@ -258,24 +368,49 @@ const imageSrc = { | ||
### Different styles depending on the theme | ||
### Programmatic usage | ||
You can use the classes `theme-dark` and `theme-light` to use different styles depending on the theme: | ||
[View example file](https://github.com/BetaHuhn/drkmd.js/blob/master/examples/programmatic/index.html) | ||
You can also control the theme programmatically. | ||
Import [drkmd.js](https://github.com/BetaHuhn/drkmd.js) like this: | ||
**HTML** | ||
```html | ||
<script src="https://cdn.jsdelivr.net/npm/drkmd-js/dist/drkmd-js.min.js"></script> | ||
``` | ||
> Note: `data-drkmd-attach` is missing because we don't want to attach the default toggle to the page | ||
or | ||
**JavaScript** | ||
```js | ||
new Darkmode().attach() | ||
import Darkmode from 'drkmd-js' | ||
``` | ||
**CSS** | ||
```css | ||
.theme-dark { | ||
/* Styles for dark theme */ | ||
Add HTML elements: | ||
```html | ||
<button id="myBtn">Click me</button> | ||
<span id="theme">Current theme:</span> | ||
``` | ||
Then create a new Darkmode instance and use any of the available methods: | ||
```js | ||
const darkmode = new Darkmode() | ||
const updateValue = () => { | ||
document.getElementById('theme').innerText = `Current theme: ${ darkmode.currentTheme() }` | ||
} | ||
.theme-light { | ||
/* Styles for light theme */ | ||
} | ||
document.getElementById('myBtn').addEventListener('click', () => { | ||
darkmode.toggle() | ||
updateValue() | ||
}) | ||
updateValue() | ||
``` | ||
> **Note:** The classes will be added to the `body` of your HTML page. | ||
## 🌍 Browser compatibility | ||
@@ -296,18 +431,18 @@ | ||
Run `yarn build` or `npm run build` to produce a production version of [drkmd.js](https://github.com/BetaHuhn/drkmd.js) in the `dist` folder. | ||
- run `yarn lint` or `npm run lint` to run eslint. | ||
- run `yarn dev` or `npm run dev` during development. | ||
- run `yarn build` or `npm run build` to produce a production version of [drkmd.js](https://github.com/BetaHuhn/drkmd.js) in the `dist` folder. | ||
## ❔ About | ||
This library was developed by me ([@betahuhn](https://github.com/BetaHuhn)) in my free time. If you want to support me: | ||
This project was developed by me ([@betahuhn](https://github.com/BetaHuhn)) in my free time. If you want to support me: | ||
[![Donate via PayPal](https://img.shields.io/badge/paypal-donate-009cde.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=394RTSBEEEFEE) | ||
### Credits | ||
[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/F1F81S2RK) | ||
The library was inspired by [Darkmode.js](https://github.com/sandoche/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 | ||
### License | ||
Copyright 2021 Maximilian Schiller | ||
Copyright 2020 Maximilian Schiller | ||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Empty package
Supply chain riskPackage does not contain any code. It may be removed, is name squatting, or the result of a faulty package publish.
Found 1 instance in 1 package
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
29437
1
437
4
5
0
2