Html, Css ve JavaScript kullanılarak herhangi bir web sitesine veya uygulamaya dark mode(Koyu renk, karanlık tema veya gece modu) uygulama nasıl yapılır.
Dark mode/Gece modu günümüzde tüm mobil cihazlarda ve hemen hemen tüm uygulamalarda mevcut olan bir seçenek. Gece modunu kullanmanın daha az enerji harcadığını ve enerji tasarrufu olduğunu da unutmamak lazım,
Aşağıda 3 kodumuz var
1. JavaScript ve 2. CSS ve 3. HTML
Html
<span class="theme-mode"></span>
Css
/*gece modu*/
/*gece modu site*/
.night-mode,
.night-mode body{
background-color: #272727 !important;
color: #fff;
}
.night-mode a{
color: #e5e5e5;
}
/*gece modu ikon*/
.theme-mode{
margin-right: 20px;
display: block;
float: left;
}
.theme-mode:hover,
.theme-mode:focus,
.theme-mode:active{
transform: rotate(180deg);
transition-duration: 1.2s;
}
.theme-mode a,
.theme-mode a:hover{
text-decoration: none;
}
.theme-mode span{
display: block;
}
.theme-mode i{
transition: all 0.2s ease;
text-decoration: none;
}
/*gece modu*/
JavaScript
/*gece modu*/ (function(window, document, undefined){
"use strict";
var nightMode = document.cookie.indexOf("nightMode=true") !== -1;
var lightMode = document.cookie.indexOf("nightMode=false") !== -1;
if (nightMode){
document.documentElement.className += " night-mode";
}else{
document.documentElement.className += " light-mode";
}
const userPrefersDark =
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches;
const userPrefersLight =
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: light)").matches;
//Önceden lihtmode seçilmemiş ise
if (!lightMode){
if (userPrefersDark){
//Cihaz koyu mod kullanıyor ise
document.documentElement.className += " night-mode";
}
}else{
if (userPrefersLight){
//Cihaz koyu mod kullanıyor ise
document.documentElement.className += " light-mode";
}
}
})(window, document);
(function(window, document, undefined){
"use strict";
var nav = document.querySelector(".theme-mode");
//HTML .theme-mode class butonu ekle
nav.innerHTML +=
'<span id="night-mode"><a role="button" title="nightMode" href="javascript:void(0);">🌓</a></span>';
var nightMode = document.querySelector("#night-mode");
nightMode.addEventListener(
"click",
function(event){
event.preventDefault();
document.documentElement.classList.toggle("light-mode, night-mode");
if (document.documentElement.classList.contains("night-mode")){
//nightMode cookie etkinleştir
return (document.cookie =
"nightMode=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/; secure;");
}
//nightMode cookie etkisizleştir
document.cookie =
"nightMode=false; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/; secure;";
},
false
);
})(window, document);
/*gece modu*/