RE: Add dark mode to any website with just a few lines of code
Tags: dark, mode, browser, javascript
Published: 2020-02-17 20:17:47



  ---     
title: RE: Add dark mode to any website with just a few lines of code
published: true
description: Make your own Chrome plugin.
tags: dark, mode, browser, javascript
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/6laqh0ygtgcmjandewe0.png
---

Today I saw [this article](https://dev.to/albertomontalesi/add-dark-mode-to-your-website-with-just-a-few-lines-of-code-5baf) by @albertomontalesi about adding a 'dark mode' to your website. I have done such a thing already years ago but in a different way (it was a chrome extension example) and since I haven't posted anything in months, why not?

Obviously this is not the ultimate way to enable a dark mode, partially because it will make anything look inverted (even images and videos) but it should be educational to at least some of you.

## Difference

Alberto talks about setting some properties in CSS and loading CSS files with JavaScript. Although I am using CSS here too, it is not stored in other files but written inline. Also, this will work on any website. Try it out and copy paste the _toggle_ function to your favorite website's console.

```js
function toggle() {
	let q = document.querySelectorAll('#nightify')
	if(q.length) {
		q[0].parentNode.removeChild(q[0])
		return false
	}
	var h = document.getElementsByTagName('head')[0],
        s = document.createElement('style');
    s.setAttribute('type', 'text/css');
    s.setAttribute('id', 'nightify');
    s.appendChild(document.createTextNode('html{-webkit-filter:invert(100%) hue-rotate(180deg) contrast(70%) !important; background: #fff;} .line-content {background-color: #fefefe;}'));
    h.appendChild(s); 
	return true
}

toggle() // woa! everything is dark!
``` 
![dark mode chrome extension](https://dev-to-uploads.s3.amazonaws.com/i/lnerkb6wjaql2q4mflst.gif)

![dark mode chrome google](https://dev-to-uploads.s3.amazonaws.com/i/ccqz2c17i9n7vw7lgl8k.gif)

![dark mode YooTjoob](https://dev-to-uploads.s3.amazonaws.com/i/swijcng66tr19t1i03wk.gif)

## localStorage
I will not talk about setting your preference in the localStorage because he does a good job explaining that.

## Chrome extension
This thing was originally a chrome extension so I'll show that bit too. If you want to [know more about how to make a chrome extension](https://dev.to/search?q=chrome%20extension), look for _chrome extension_ here on dev.to for some fine articles.

### manifest.json

This JSON file says the extension wants permission to access every tab, a browser action button will be added to the chrome menu and it will load background script _script.js_ which you can find below.

```json
{
    "name": "NightTime",
    "version": "1.0",
    "manifest_version": 2,
    "description": "Toggle the darkness.",
    "permissions": [
      "<all_urls>"
     ],
    "browser_action": {
      "name": "Nighty"
    },
    "background": { 
      "scripts": ["script.js"]
    }
}
```

### script.js
```js
chrome.browserAction.onClicked.addListener(tab => { //Fired when User Clicks ICON
    chrome.tabs.executeScript(tab.id, {
            "file": "contentscript.js"
        }, result => { // last statement of contentscript
            console.log("Toggle night time...") // Notification on Completion
    })
})
```

### contentscript.js

This _toggle_ function is the same as above. The last line _result = toggle()_ reflects the result in _script.js_ right before the call to console.log. Our toggle function basically says here that if our _style_ element already exists, remove it. If it doesn't, add it.

```js
function toggle() {
	let q = document.querySelectorAll('#nightify')
	if(q.length) {
		q[0].parentNode.removeChild(q[0])
		return false
	}
	var h = document.getElementsByTagName('head')[0],
        s = document.createElement('style');
    s.setAttribute('type', 'text/css');
    s.setAttribute('id', 'nightify');
    s.appendChild(document.createTextNode('html{-webkit-filter:invert(100%) hue-rotate(180deg) contrast(70%) !important; background: #fff;} .line-content {background-color: #fefefe;}'));
    h.appendChild(s); 
	return true
}

var result = toggle()
```

That's all!