Dark mode switch not staying on?

I’m trying to make dark mode stay enabled. Putting the code in the masterpage does nothing like somebody had suggested before. Can one of you help?

Here’s the code:

import { session } from ‘wix-storage’ ;

session . setItem ( “key” , “value” );

$w . onReady ( function () {
$w ( ‘#darkModeSwitch’ ). onChange ( function () {
if ( $w ( ‘#darkModeSwitch’ ). checked ) {
$w ( ‘Document’ ). background.src = “https://static.wixstatic.com/media/75b29a_93116c1bc83f434ebada916aa9cb21c4~mv2.png
$w ( ‘#darkModeState’ ). text = “Night”
} else {
$w ( ‘Document’ ). background.src = “https://static.wixstatic.com/media/75b29a_49383cb5556f46beb603f8d4c93e57b5~mv2.png
$w ( ‘#darkModeState’ ). text = “Night” }
});
});

Would love to FINALLY be able to get this to work… If anyone knows I’d appreciate it, thank you

You should save the state in memory.
something like:

//masterPage.js
import {session} form 'wix-storage';
let isDark = session.getItem('isDark');
$w.onReady(() => {
if(isDark){
	$w('#darkModeSwitch').checked = true;
	handleMode(isDark);
}
 $w('#darkModeSwitch').onChange(event => {
 isDark = event.target.checked;
 handleMode(isDark);
 isDark ? session.setItem('isDark', 'true') : session.removeItem('isDark');
 });
})

function handleMode(isDark){
if(isDark){
$w('Document').background.src = darkImageUrl;
 $w('#darkModeState').text = "Night";
} else {
$w('Document').background.src = lightImageUrl;
 $w('#darkModeState').text = "Light"
}
}

(UPDATED)

This actually worked! Thank you so much!!!

Hello Inter,

Im facing some issues with the dark mode in Editor X.
Could you share your final code working well pleeeaaase ?

Thanks for your support !