Enable Light / Dark Mode on Website
It is common with many iOS apps to offer users the option of a light or dark interface that automatically detects the users Night Shift settings. This following script brings that functionality to your website allowing you to create the same app-like experience. It automatically detects the users Night Shift settings but can also be overridden with a button that stores a cookie in the users browser. When enabled it adds an additional class to your body tag called dark-mode-enabled.
See it in action on Codepen
$(document).ready(function() {
//check if this is user's first time on page
if(!getCookie('Theme')){
console.log("Should only ever run once");
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
currentTheme = "dark";
} else {
currentTheme = "light";
}
} else {
currentTheme = getCookie('Theme');
}
setTheme(currentTheme);
});
$(".dark-toggle").on("click", function () {
if ($("body").hasClass("dark-mode-enabled")) {
setTheme('light');
} else {
setTheme('dark');
}
});
// DARK MODE TOGGLE FUNCTION
var setTheme = function (theme) {
if (theme === 'dark') {
$("body").addClass("dark-mode-enabled");
$(".dark-toggle").text("Dark");
setCookie('Theme', 'dark', 999);
} else {
$("body").removeClass("dark-mode-enabled");
$(".dark-toggle").text("Light");
setCookie('Theme', 'light', 999);
}
};
// COOKIE HANDLING
function getCookie(name) {
var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
return v ? v[2] : null;
}
function setCookie(name, value, days) {
var d = new Date;
d.setTime(d.getTime() + 24 * 60 * 60 * 1000 * days);
document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
}
function deleteCookie(name) {
setCookie(name, '', -1);
}
Display the button anywhere on your site with the following HTML code:
<button class="dark-toggle">Dark</button>
Use the following CSS class to style any element on your site:
body.dark-mode-enabled{
background: black;
}

Leave a Reply
Want to join the discussion?Feel free to contribute!