I've created dark mode for my website with HTML, CSS, and javascript.
here is my javascript code:
var $jDarkMode = jQuery.noConflict();
$jDarkMode(document).ready(function($) {
var darkModeToggle = $('#darkModeToggle');
var body = $('body');
var setDarkModePreference = function(value) {
localStorage.setItem('darkMode', value);
};
var updateDarkMode = function() {
var darkModePreference = localStorage.getItem('darkMode');
if (darkModePreference === 'true') {
body.addClass('dark-mode');
darkModeToggle.prop('checked', true);
} else {
body.removeClass('dark-mode');
darkModeToggle.prop('checked', false);
}
};
darkModeToggle.on('change', function() {
if (darkModeToggle.prop('checked')) {
body.addClass('dark-mode');
setDarkModePreference(true);
} else {
body.removeClass('dark-mode');
setDarkModePreference(false);
}
});
updateDarkMode();
});
I tried to create a save statement. So if the user activates the dark mode once, it will be saved in the browser, and if the browser is closed or the page is refreshed, etc., because the dark mode has been activated before, the dark mode will be active. But something is not working right.
It works in such a way that every time the page is loaded, it is first shown with the default light mode, and then the dark mode is activated.
It seems to stay for a few seconds and then the toggle button is pressed automatically and then dark is activated. And all this can be seen with the eyes!
Is it possible to save the settings in the browser so that as soon as the screen is loaded, the light screen will not be seen at all and the dark mode will be activated from the beginning and everything will be loaded with dark mode from the beginning? When it is saved, the movement of the toggle button can no longer be seen and it is saved in the same mode from the beginning.
Is my method wrong? I did not write the code correctly. Is this possible with JQuery/JavaScript, or is the language limited in this; And should we go to PHP?!