I'm having trouble with prefers-color-scheme with the logic that I'm trying to achieve. For example, with the prefers-color-scheme I have a toggle on my site that overrides this is a user prefers black while using light mode, and vice versa. The issue I'm running into is I can't toggle it so that when a user changes the toggle to set it to the OS color theme, when they switch pages the theme switches back to the prefers color scheme. I already have local storage setup and variables called theme type and on.
When I comment out the detect color scheme function, the local storage remembers the users desired theme setting. When uncommented it overrides and always picks the theme os color scheme. How can I get my logic working right where when on the users first entry point before the local storage is created that it reads the theme OS but if the user changes the theme to black and vice versa that the OS doesn't override when on page change?
Thanks.
So the detectColorScheme checks users OS theme.
function detectColorScheme(){
var on = 1;
on = 1;
if (window.matchMedia('(prefers-color-scheme: dark)').matches && on <= 1) {
if (on = 1 ) {
on = 2;
darkmode();
console.log("OS Setting DARK MODE");
}
}
if (window.matchMedia("(prefers-color-scheme: light)").matches ) {
if (on = 1) {
lightmode();
console.log("OS Setting LIGHT MODE");
}
}
}
Then at the start of the javascript file I do the following :
document.body.style.backgroundColor = "";
if (localStorage.themepref == 1 ) {
detectColorScheme();
document.body.style.backgroundColor = "#FFF";
lightmode();
}
else {
detectColorScheme();
document.body.style.backgroundColor = "#0a0a0a";
darkmode();
localStorage.themepref = 2;
}
window.onload = function() {
console.log('First');
if (event.target.readyState === 'loading') {
detectColorScheme();
$('body').css({ background: ''});
document.body.style.backgroundColor = "inherit";
if(lightmodeON == true) {
detectColorScheme();
$('body').css({background: "#fbfcfd"});
document.body.style.backgroundColor = "#FFF";
}
if(lightmodeON == false) {
detectColorScheme();
$('body').css({background: "#0a0a0a"});
document.body.style.backgroundColor = "#0a0a0a";
}
}
};
And lastly
document.addEventListener("DOMContentLoaded", function() {
window.scrollTo(0, 0);
$(window).scrollTop( $("#top").offset().top );
$(document).scrollTop(0);
document.body.style.backgroundColor = "";
if (document.readyState === 'complete') {
if(lightmodeON == true) {
$('body').css({background: "#fbfcfd"});
console.log('loading white bg');
}
if(lightmodeON == false) {
$('body').css({background: "#0a0a0a"});
console.log('loading black bg');
}
}
if (typeof (Storage) !=="undefined") {
if (localStorage.themepref == 1 ) {
lightmode();
}
else {
darkmode();
localStorage.themepref = 2;
}
if(lightmodeON == true) {
$('body').css({background: "#fbfcfd"});
console.log('loading fffwhite bg');
}
if(lightmodeON == false) {
$('body').css({background: "#0a0a0a"});
console.log('loading black bg');
}
}