code everywhere

adding a dark mode toggle to any website

posted on November 8, 2022, 11:33 pm in css, js, html

Dark mode has become very popular in the past few years, it makes reading websites easier and saves power when viewing on OLED screens. Heres how we can implement a generic dark mode toggle to any website. By using cookies, the state is consistent as you move across the website.

The code works by toggling a "darkmode" class on the main body element, and adding the accompanying CSS styles.

Code

// file: darkmode.js

let a document.createElement('a');
a.innerHTML '♠';
a.style 'border-radius:25px; position: absolute; top: 5px; right: 5px; padding: 2px 5px 2px 5px; cursor: pointer; background: grey; text-align:center; display: block;';
a.addEventListener('click', function() {
    
let body document.getElementsByTagName('body')[0];
    if(
body.className.indexOf('darkmode')>-1){
        
body.classList.remove('darkmode');
        
document.cookie "darkmode=; expires=Thu, 01 Jan 1970 00:00:01 GMT";
    } else {
        
body.classList.add('darkmode');
        
document.cookie "darkmode=true";
    }                    
})
document.getElementsByTagName('body')[0].appendChild(a);
if( 
document.cookie.indexOf('darkmode') > -)
    
document.getElementsByTagName('body')[0].classList.add('darkmode');

Add this to the bottom of your page by creating a file;

<script type="text/javascript" src="darkmode.js"></script>

Modify the CSS to fit your existing content;

.darkmode body {
    
background-colorblack;
    
colorwhite;
}

Using Media Query

You can also use the standard @media to modify your styles based on the system default.

@media (prefers-color-schemedark) {
    
body {    
        
background-colorblack;
        
colorwhite;
    }
}

@
media (prefers-color-schemelight) {
    
body {    
        
background-colorwhite;
        
colorblack;
    }
}

recent posts

< back
find something helpful? send us some coin BTC 19u6CWTxH4cH9V2yTfAemA7gmmh7rANgiv

(ad) Need Hosting? Try Linode, VPS Starting from $5

privacy policy