DEV Community

Cover image for RE: Add dark mode to any website with just a few lines of code
Jochem Stoel
Jochem Stoel

Posted on

RE: Add dark mode to any website with just a few lines of code

Today I saw this article 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.

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

dark mode chrome google

dark mode YooTjoob

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, 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.

{
    "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

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.

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!

Top comments (1)

Collapse
 
mzaini30 profile image
Zen

Your code + localStorage:

buat_dark = () => {
    // ini kalau q.length nggak jalan / elemen belum ada
    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); 
    localStorage.setItem('dark', 'true')
    return true
}

localStorage.dark == 'true' ? buat_dark() : ''

function dark() {
    let q = document.querySelectorAll('#nightify')
    if(q.length) {
        // ini kalau elemen sudah ada
        q[0].parentNode.removeChild(q[0])
        localStorage.removeItem('dark')
        return false
        // false berarti hentikan proses
    }
    buat_dark()
}

$(".dark").click(() => dark())

$("body").css("min-height", $(window).height())