Why does reading localStorage values require a page refresh to show CSS changes toggled by jQuery?
You have multiple issues in you code. First, you toggle the CSS, but only when the page loads because this code is only run once (when the script is loaded):
if (localStorage.toggled === 'dark') {
// ...
Just move this script in the function (ex: updateInterfaceTheme
) that you call at the end of darkLight()
.
Another issue is that you forget to clean the previous class and that leads to a styling conflict:
$('.twitter-light-display-none').addClass("display-none"); // class .display-block still exist
$('.twitter-dark-display-none').addClass("display-block"); // class .display-none still exist
So don't forget to clean them:
if (localStorage.toggled === 'dark') {
$('.twitter-light-display-none').addClass("display-none").removeClass('display-block');
$('.twitter-dark-display-none').addClass("display-block").removeClass('display-none');
} else {
$('.twitter-dark-display-none').addClass("display-none").removeClass('display-block');
$('.twitter-light-display-none').addClass("display-block").removeClass('display-none');
}
And like that it's working:
function darkLight() {
if (localStorage.toggled !== 'dark') {
$('body').toggleClass('dark', true);
localStorage.toggled = "dark";
} else {
$('body').toggleClass('dark', false);
localStorage.toggled = "";
}
updateInterfaceTheme();
}
function updateInterfaceTheme() {
if (localStorage.toggled === 'dark') {
$('.twitter-light-display-none').addClass("display-none").removeClass('display-block');
$('.twitter-dark-display-none').addClass("display-block").removeClass('display-none');
} else {
$('.twitter-dark-display-none').addClass("display-none").removeClass('display-block');
$('.twitter-light-display-none').addClass("display-block").removeClass('display-none');
}
}
updateInterfaceTheme()
.display-none {
display: none !important;
}
.display-block {
display: block !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="switch"><span class="switchtext">Dark</span>
<input type="checkbox" data-style="ios" data-onstyle="outline-secondary" data-offstyle="outline-secondary" data-size="sm" data-toggle="toggle" onchange="darkLight()">
<span class="slider"></span><span class="switchtext">Mode</span>
</label>
<div class="twitter-dark-display-none">Dark Mode
<a class="twitter-timeline" data-width="170" data-height="200" data-theme="dark" data-tweet-limit="1" data-chrome="transparent nofooter noborders" href="https://twitter.com/StackOverflow?ref_src=twsrc%5Etfw">Tweets</a>
</div>
<div class="twitter-light-display-none">Light Mode
<a class="twitter-timeline" data-width="170" data-height="200" data-tweet-limit="1" data-chrome="transparent nofooter noborders" href="https://twitter.com/StackOverflow?ref_src=twsrc%5Etfw">Tweets</a>
</div>