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;
}
});
Related
I have a problem where i am trying to disable certain forms fields which use the SelectStatic Widget based on a tick box, i have included the javascript below.
const vlan = document.querySelector('#id_vlan');
const physical_facing = document.querySelector('#id_physical_facing');
const service_type = document.querySelector('#id_service_type');
const bd_function = document.querySelector('#id_function');
function vlan_enable(){
vlan.disabled = false;
};
function vlan_disable(){
vlan.disabled = true;
};
function service_function_enable() {
service_type.disabled = false;
bd_function.disabled = false;
};
function service_function_disable() {
service_type.disabled = true;
bd_function.disabled = true;
};
(function() {
service_function_enable();
vlan_enable();
if(physical_facing.checked){
service_function_disable();
} else {
vlan_disable();
}
})();
function pf_event() {
if(physical_facing.checked) {
vlan_enable();
service_function_disable();
} else {
vlan_disable();
service_function_enable();
}
};
physical_facing.addEventListener('change', pf_event)
When on the Page, the VLAN field is a DynamicModelFormField and will never disable, but when toggling the switch on and off the fields do not re-enable, i know the event is getting fired because i can see it in the developer tools, the disabled tag gets applied and removed with no change on the page, This may be a simple mistake but would like if someone can point me in the right direction.
below is what the page looks like
Netbox Page
Has anybody had any success doing this with the new version of netbox as it worked fine in V2 with the SelectStatic2 widget.
I am developing my web developer portfolio. In that when I press the hamburger, the color of the top nav bar should also change. But sometimes in Chrome it doesn't change and I have to reload. I thought it is probably because the script didn't load. But even after waiting for a long time this bug occurs. Can anyone say why it happens and how to solve it. Note that this color change is only for mobile nav. The source code is available at https://github.com/mrjithin/my-portfolio/ . And the script that does this thing is available with the name ham.js in the scripts folder.
The top color should have been the same as the color of the rest of the navbar.
// ham.js
// For mobile hamburger
const mobNav = document.querySelector("nav#mobile");
const deskNav = document.querySelector("nav.desktop");
const navColor = window.getComputedStyle(mobNav).getPropertyValue("background-color");
document.getElementsByClassName("ham")[0].addEventListener("click", (event) => {
document.getElementsByClassName("ham")[0].classList.toggle("cross");
document.getElementById("line2").classList.toggle("none");
mobNav.classList.toggle("on");
mobNav.classList.toggle("off");
if(mobNav.className === "on"){
deskNav.style.backgroundColor = navColor;
} else {
deskNav.style.backgroundColor = "";
}
event.stopPropagation();
});
// To close the navbar on clicking a link.
const mobileLis = document.querySelectorAll("nav#mobile a");
Array.from(mobileLis).forEach(link => {
link.addEventListener("click", event => {
document.getElementsByClassName("ham")[0].classList.toggle("cross");
document.getElementById("line2").classList.toggle("none");
mobNav.classList.toggle("on");
mobNav.classList.toggle("off");
if(mobNav.className === "on"){
deskNav.style.backgroundColor = navColor;
} else {
deskNav.style.backgroundColor = "";
}
event.stopPropagation();
})
})
Thanks in advance!
Instead of this code
const navColor = window.getComputedStyle(mobNav).getPropertyValue("background-color");
try this one
const navColor = () => window.getComputedStyle(mobNav).getPropertyValue("background-color");
And call navColor as a function navColor()
first time caller here, please be gentle..
I am in the process of my JavaScript reflection and having a problem with the cookie modal. You need to be able to have the cookie pop up upon entering the site, the user needs to click ok, it is stored locally, and doesn't pop up if the user refreshes the browser.
I have created a basic modal and written the JavaScript, which partly works, but the eventHandler isn't working.
The cookie value is false, which you can see in the console, but when you click the button, it doesn't turn to true.
I have put the code below and if anyone could help I'd really appreciate it.
<div id ="overlay">
<div class="modal">
<p>
</p>
</div>
<button class="settings_button">CHANGE SETTINGS</button>
<button class="modal_accept_button">ACCEPT COOKIES</button>
<button class="modal_accept_button">Accept</button>
</div>
let modalObject = document.querySelector(".modal");
let modalSettings = document.querySelector('.settings_button');
let modalAccept = document.querySelector('.modal_accept_button');
let modalOverlay = document.querySelector("#overlay");
function showModal() {
modalObject.classList.remove('deactive');
modalOverlay.classList.remove('deactive');
}
function disableModal() {
modalObject.classList.add('deactive');
modalOverlay.classList.add('deactive');
}
localStorage.setItem('cookie', 'false');
window.addEventListener('DOMContentLoaded', () => {
if (localStorage.getItem('cookie') == 'true') {
console.log("Cookie is already in place.");
} else if (localStorage.getItem('cookie') === null ||
localStorage.getItem("Cookie accepted") == 'false') {
console.log("Cookie has been not yet been accepted.");
showModal();
modalAccept.addEventListener('click', () => {
localStorage.setItem('cookie','true');
disableModal() ;
});
}
});
You have localStorage.setItem('cookie', 'false'); in your code and this changes your ls to false every time that your codes run, just remove it and I think it's better if you save your local storage in a variable then use that variable in your if statement:
const modal = document.querySelector('.modal');
const acceptBtn = document.querySelector('#acceptCookies');
(() => {
const isCookieAccepted = JSON.parse(window.localStorage.getItem('cookie'));
if (isCookieAccepted) {
alert(`Cookie status: ${isCookieAccepted}`)
} else {
modal.classList.add('show')
}
})();
acceptBtn.addEventListener('click', () => {
window.localStorage.setItem('cookie', true);
modal.classList.remove('show')
})
In your code, you have a line that sets it to false:
localStorage.setItem('cookie', 'false');
This will always set it to false every time you go to that page. So even if you set it to true, when you refresh it will be back to false again.
Removing that line should work, as you dont need to set it to false
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
Hi, I have been coding a little Js function that manipulates certains divs and elements. On firefox it works great, but it does not work in Chrome and halts all the Javascript. I simply don't find what is wrong. Could you be kind enough to let me know? Cookies were tested and work fine. Using Jquery. Thanks!
function RememberMe(addr, bycookie = false)
{
// Cookie name
cookiename = "LBETS";
// Should we reset?
reset = false;
changed = false;
// See if button pressed
if($(".star_"+ addr).hasClass("active"))
{
$('#recent_tx').addClass("table-striped");
$(".star_"+ addr).removeClass("active");
reset = true;
} else {
$(".favstar").removeClass("active");
}
// Iterate rows
$('#recent_tx tr').each(function(){
if($(this).hasClass(addr))
{
if(reset)
{
$(this).removeClass('warning');
} else {
$(this).addClass('warning');
changed = true;
}
} else {
$(this).removeClass('warning');
}
})
// Change class
if(changed)
{
$('#recent_tx').removeClass("table-striped");
$(".star_"+ addr).addClass("active");
setCookie(cookiename, addr, 20*365);
}
// Reset
if(reset)
{
delCookie(cookiename);
}
}
Invalid syntax:
function RememberMe(addr, bycookie = false)
You can't do assignment of defaults in the function signature.
Firefox's JS engine allows this syntax, and it is likely coming in some form to ECMAScript 6.