Dark mode checkbox should be saved in local storage - javascript

I'm trying to implement a dark mode - light mode switcher on my website. I don't really know anything about JS but I played around with the code snippets I found online and put together something that kind of works.
What I have so far:
- I have two sets of colors in CSS that I can switch between with a checkbox in the navbar.
- I also found out how I can store a checkbox's state locally, so if I turn on the dark mode and then navigate to another page, the checkbox is still checked.
The problem is that every time I navigate to another page, the checkbox gets unchecked first and then it realises that it has to be checked and it checks itself automatically. But it takes time, there's even an animation which is kind of annoying because if I check it on a page, I want it to be checked by default on all the other pages until I turn it off.
Here's a video that explains it better: https://drive.google.com/file/d/1y48yh1h1bGM6abrthVmtUD8azVuDG4yE/view?usp=sharing
Any help would be appreciated since I really don't know what's going on here :D
// DARK MODE SWITCHER
var checkbox = document.querySelector('input[name=mode]');
checkbox.addEventListener('change', function() {
if(this.checked) {
trans()
document.documentElement.setAttribute('data-theme', 'dark')
} else {
trans()
document.documentElement.setAttribute('data-theme', 'light')
}
})
let trans = () => {
document.documentElement.classList.add('transition');
window.setTimeout(() => {
document.documentElement.classList.remove('transition');
}, 1000)
}
// SAVE DARK MODE CHECKBOX STATE IN LOCAL STORAGE
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
$checkboxes = $("#checkbox-container :checkbox");
$checkboxes.on("change", function(){
$checkboxes.each(function(){
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
// On page load
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', value);
});

the jsfiddle solution :
https://jsfiddle.net/zhbo40ma/
you need to set your theme at page load :
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', value);
if($('#'+key).attr('name') == 'mode') {
if(value) {
trans();
document.documentElement.setAttribute('data-theme', 'dark')
}
else {
trans();
document.documentElement.setAttribute('data-theme', 'light')
}
}
});
don't forget to write your trans() function before your page load function cause you declare it with a let

Related

Move color of an HTML element to another page

Good evening,
i was working on a part of what i hope will be my future website and i wanted to add a "photograpy" section to it, and here comes the problem.
since the title in the main page constatly changes color, i'd like to grab its current color to transfer it to the title of the other page to play an animation later on.
the problem is that when i press the related button, i am taken to the photograpy page, but the title remains black.
i've tried seraching for help on google but i haven't been able to find much.
here is the JS
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", function() {
loaded();
});
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", function() {
loaded();
});
}
function loaded() {
document.getElementById("PHtitle").style.color === titlecolor;
}
function script() {
const titlecolor = document.getElementById("title").style.color;
};
document.getElementById('photograpy').onclick = function () {
script();
};
The snippets don't allow for localStorage, so here is just the javascript.
First, I let the variables outside of a function. The titleColor function checks to see if titleColor was saved in localStorage, if not the default color is black.
Then I set the color of the phtitle to the contents of titleColor variable.
In the script function, I set the localStorage variable to the getComputedStyle color of the title.
Then last I use an event listener on the button to run the script for saving the color.
LocalStorage is a way to store data in the user's browser until they close their browser/clear their data etc.. Which will allow it to be usable on different pages then where it was saved.
let titleColor = localStorage.getItem("titleColor") || "#000000";
let PHtitle = document.querySelector("#PHtitle");
let title = document.querySelector("#title");
let btn = document.querySelector("#photography");
if(PHtitle){
PHtitle.style.color = titleColor;
}
function script() {
localStorage.setItem("titleColor", getComputedStyle(title).color)
}
if(btn && title){
btn.addEventListener("click", function() {
script();
})
}

Issue with Saving Dark Mode Preference (localStorage)

I am trying to use localStorage to save the dark mode preference on my website. The issue I am running into is when you switch to dark mode and hit refresh, it stays in dark mode. However, if you switch to dark mode, then back to light mode, and hit refresh, it loads dark mode.
I am stuck so far and haven't been able to find any helpful resources on this yet.
Here is my fiddle along with my js script below.
Fiddle
Javascript
$(document).ready(function(){
$('ul').click(function(){
$('ul').toggleClass('active')
let darkThemeEnabled = $('section').toggleClass('dark');
localStorage.setItem('dark-theme-enabled', darkThemeEnabled);
})
})
if (localStorage.getItem('dark-theme-enabled')) {
$('section').toggleClass('dark');
$('ul').toggleClass('active');
}
You need to set a Boolean to localStorage:
$("section").toggleClass("dark");
let darkThemeEnabled = $("section").hasClass("dark");
localStorage.setItem("dark-theme-enabled", darkThemeEnabled);
EDIT
Also change your getting method:
if (localStorage.getItem('dark-theme-enabled')) {
$('section').addClass('dark');
$('ul').addClass('active');
}
This worked for me (i put my dark-mode on my body):
const body = document.querySelector('body');
const checkBox = document.getElementById('checkbox');
window.addEventListener('load', () => {
if (!localStorage.dark_mode)
localStorage.dark_mode = false;
else if (JSON.parse(localStorage.dark_mode) === true) {
body.classList.add('dark-mode');
checkbox.checked = true;
}
});
checkBox.addEventListener('click', (e) => {
body.classList.toggle('dark-mode');
if (body.classList.contains('dark-mode')) {
checkbox.checked = true;
localStorage.dark_mode = true;
}
else {
checkbox.checked = false;
localStorage.dark_mode = false;
}
});

JQuery, .attr - Remember state using cookies after page reload

I wrote a function that changes logo to minimised version of it when I click on a button by changing attribute of an image. Also, after another click on the same button, logo switches back to original.
Everything is as I expected but I have a problem when I refresh the page. When I refresh the page, the browser just switches the logo back to original. So, I want the browser to remember if logo is switched and remember that state after reload of page. Please see my code below. I've seen similar solutions here but I don't know how to implement it in my code.
How can I set and use cookies for this?
$('#changeLogo').click(function() {
if ($(".logo").attr('src') === "files/img/logo-min.png") {
$(".logo").attr('src', "files/img/logo.png");
}
else {
$(".logo").attr('src', "files/img/logo-min.png");
}
});
Localstorage is a better option for this:
$(function(){
$('#changeLogo').click(function() {
var logoSrc;
if ($(".logo").attr('src') === "files/img/logo-min.png") {
logoSrc = "files/img/logo.png";
}
else {
logoSrc = "files/img/logo-min.png";
}
$(".logo").attr('src', logoSrc);
localStorage.setItem("logoSrc", logoSrc);
});
if ( typeof localStorage.logoSrc !== "undefined" )
$(".logo").attr('src', localStorage.logoSrc);
});
$(document).ready(function(){
var logo = localStorage.getItem('logo');
if(logo != null){
$(".logo").attr('src', logo);
}
$('#changeLogo').click(function() {
if ($(".logo").attr('src') === "files/img/logo-min.png") {
$(".logo").attr('src', "files/img/logo.png");
}
else {
$(".logo").attr('src', "files/img/logo-min.png");
}
localStorage.setItem('logo',$(".logo").attr('src'));
});
});
Set src in localStorage and on page load get the value and set the src again to logo.
You can set cookies using javascript api: https://www.w3schools.com/js/js_cookies.asp
Or use an easier api like this:
https://github.com/js-cookie/js-cookie
So in the if/else you can save the currently used link of the logo to a cookie:
//set
Cookies.set('logo-path', 'files/img/logo-min.png');
//get
Cookies.get('logo-path');
You could also utilize local storage (https://www.w3schools.com/html/html5_webstorage.asp) but it is not guaranteed that it will work on older browsers.
If you want to use cookies, you can use the JQuery plugin http://plugins.jquery.com/cookie/
Then :
$(document).ready(function(){
if (typeof $.cookie('logo') === 'undefined')
$.cookie('logo', "files/img/logo-min.png");
$('#changeLogo').click(function() {
if ($.cookie('logo') === "files/img/logo-min.png") {
$.cookie('logo', "files/img/logo.png");
} else {
$.cookie('logo', "files/img/logo-min.png");
}
$(".logo").attr('src', $.cookie('logo'));
});
});

How do I persist the checkbox status after click event/jQuery/ajax call

I have the following event code that reloads a code section on my page. The problem is that, if the check box is checked, I can't find a way to re-check it after the reload.
jQuery(this.el).find('.view_all_future_filter').click(function () {
TodoNote.view_all_future_filter = jQuery(this).prop('value');
_this.parent.reload();
})
I tried the following, but the check box keeps being reset to unchecked:
if(this.view_all_future_filter == "on") {
this.query_string += '&view_all_future_filter=' + this.view_all_future_filter;
var show_state = "checked";
} else {
var show_state = "";
}
this.load();
jQuery('#view_all_future_filter').prop('checked', show_state);
Any help would be greatly appreciated!
You can use sessionStorage to save data and get it after reload content:
if (window.sessionStorage) {
var checkedState = jQuery('#view_all_future_filter').attr('checked');
sessionStorage.setItem("someCheckboxState", checkedState);
}
And when content loaded to page:
if (window.sessionStorage) {
var checkedState = sessionStorage.setItem("someCheckboxState");
jQuery('#view_all_future_filter').attr('checked', checkedState);
}
Note: If you are using jQuery 1.6+ you must change attr to prop for boolean properties as checked, disabled and etc.
You could store the checkbox status in a cookie. Then, in an onload callback, initialize the checkbox status from the cookie.

Browser - Force reload deleting cookies?

I have created a page with a select input to change the jQuery UI theme in use. When the theme is changed, it is stored in a cookie. When the page loads, if the cookie exists, the theme is restored, else a default theme is loaded.
My code does work when i refresh the page using F5, but if i force a complete reload using ctrl + F5, it doesn't. Is it a problem in my code or is it a normal effect ?
Here is my code if needed :
(function($) {
$(function() {
var $themeSelect = $('#themeSelect');
var initialTheme = $.cookie('theme');
$themeSelect.on('change', function() {
var dir = 'jQueryUI/css/' + $themeSelect.val();
$('#uiThemeA').attr('href', dir + '/jquery-ui.min.css');
$('#uiThemeB').attr('href', dir + '/jquery.ui.theme.css');
$.cookie('theme', $themeSelect.val());
});
if(initialTheme !== undefined) {
$themeSelect.children().each(function(index, element) {
var $element = $(element);
if($element.attr('selected')) {
$element.removeAttr('selected');
}
if($element.attr('value') === initialTheme) {
$element.attr('selected');
}
}).trigger('change');
} else {
$.cookie('theme', $themeSelect.val());
}
});
})(jQuery);
Thanks for your help !
I found the problem :
There was a mistake in my code :
if($element.attr('value') === initialTheme) {
$element.attr('selected');
}
Should be :
if($element.attr('value') === initialTheme) {
$element.attr('selected', 'selected');
}
And no, a forced reload doesn't delete cookies.

Categories

Resources