7

I'm trying to use the value of localStorage to display one of two Twitter feeds, one for a light mode theme, the other for dark mode. It works, but I have to refresh the webpage for the correct CSS - either twitter-dark-display-none or twitter-light-display-none - to work.

Using jQuery(document).ready(function () doesn't help.

The Fiddle: https://jsfiddle.net/zpsf5q3x/2/ But the sample tweets don't show due to JSFiddle limits on displaying third party frames. And, localstorage may not work there, either.

Fiddle calls two external libraries: https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css and https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js

HTML:

Note the data-theme="dark" in the first block.

<div class="twitter-dark-display-none">
<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">
<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>

jQuery:

Overall function that uses localStorage to toggle the entire site between dark and normal mode.

$('body').toggleClass(localStorage.toggled);
function darkLight() {
  if (localStorage.toggled != 'dark') {
    $('body').toggleClass('dark', true);
    localStorage.toggled = "dark";
  } else {
    $('body').toggleClass('dark', false);
    localStorage.toggled = "";
  }
}

What I'm trying to use to toggle CSS:

  if (localStorage.toggled === 'dark') {
    
        $('.twitter-light-display-none').addClass("display-none");
        $('.twitter-dark-display-none').addClass("display-block");
    
      } else {
    
        $('.twitter-dark-display-none').addClass("display-none");
        $('.twitter-light-display-none').addClass("display-block");
    
    }

CSS:

.display-none {
    display: none !important;
}

.display-block {
    display: block !important;
}

Edit 10/24/2020:

johannchopin's answer works, with the addition of $('body').toggleClass(localStorage.toggled); as in my original code above.

But. There is some sort of conflict with the gitbrent dark mode JS and CSS libraries, so I switched to https://github.com/coliff/dark-mode-switch and that results in a simpler way to both toggle dark mode and use localstorage in addition to the function johannchopin provided to switch between twitter widget divs:

<script>

(function() {
  var darkSwitch = document.getElementById("darkSwitch");
  if (darkSwitch) {
    initTheme();
    darkSwitch.addEventListener("change", function(event) {
      resetTheme();
    });
    function initTheme() {
      var darkThemeSelected =
        localStorage.getItem("darkSwitch") !== null &&
        localStorage.getItem("darkSwitch") === "dark";
      darkSwitch.checked = darkThemeSelected;
      darkThemeSelected
        ? document.body.setAttribute("data-theme", "dark")
        : document.body.removeAttribute("data-theme");
    }
    function resetTheme() {
      if (darkSwitch.checked) {
        document.body.setAttribute("data-theme", "dark");
        localStorage.setItem("darkSwitch", "dark"); 
} else {
        document.body.removeAttribute("data-theme");
        localStorage.removeItem("darkSwitch");  
      }
  updatedarkSwitch();
    }
  }
})();

function updatedarkSwitch() {
  if (localStorage.darkSwitch === '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');
  }
}
updatedarkSwitch()
</script>

And then use the most basic dark mode rule in the style sheet:

[data-theme="dark"] {
background-color: #000000 !important;
}

and also add any other more specific CSS rules needed, i.e.

[data-theme="dark"] .post-title{
color:#fff !important;
}
BlueDogRanch
  • 721
  • 1
  • 16
  • 43
  • 1
    Please add all of the code necessary to reproduce the issue in your jsfiddle. We need to see the behavior + the code in order to help – Andrew Oct 14 '20 at 22:05
  • 1
    All the code is there; the tweets don't show due to JSFiddle limits on displaying third party frames. And, localstorage may not work there, either. – BlueDogRanch Oct 14 '20 at 22:08
  • 1
    Check your jsfiddle again. Your JavaScript is not wired up to the buttons. All you have there is an if/else statement. Where are your event listeners? – Andrew Oct 14 '20 at 22:13

2 Answers2

6

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>

Checkout the jsfiddle to see it working with localStorage.

react_or_angluar
  • 1,568
  • 2
  • 13
  • 20
johannchopin
  • 13,720
  • 10
  • 55
  • 101
  • 1
    Thanks! That's a good try, but dark/light mode doesn't persist across page reloads or navigation to other pages; dark/light mode gets toggled off with a page reload. – BlueDogRanch Oct 18 '20 at 15:33
  • 1
    @BlueDogRanch Yes it. Switch to dark mode and refresh the page, you will see that only the `Dark Mode Tweets` text is shown. Switch again to light and refresh, you will just see the `Light Mode Tweets` text. If you speak about the checkbox you didn't write any code about this one. Should I add this feature to the answer? – johannchopin Oct 18 '20 at 15:37
  • 1
    The original code in my question *correctly allows dark/light mode to persist across page loads*; that was never the problem. The problem has always been forcing the CSS on the twitter divs to display correctly *without needing to refresh* the page. – BlueDogRanch Oct 18 '20 at 15:46
  • 1
    What do you mean with `dark/light mode gets toggled off with a page reload`? Check the [jsfiddle](https://jsfiddle.net/0bmLnfh5/19/) and you will see that on page reload the correct section is shown according to the theme (so it is persistant) :/ What feature exactly is missing in my code? the checkbox that still check on dark mode? – johannchopin Oct 18 '20 at 15:52
  • 1
    Ah, one problem is that I have in my Fiddle two included libraries: https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css and https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js . But, I have those, of course, in my localhost, and still the dark/light mode does not persist across page loads. – BlueDogRanch Oct 18 '20 at 16:00
  • 1
    @BlueDogRanch Please explain what `still the dark/light mode does not persist across page loads` mean??? What do you mean by that??? In my jsfiddle it is working like expected so you probably have another issue in you code that you don't mention in the question – johannchopin Oct 18 '20 at 16:09
  • 1
    Ah, hah; the problem is we're missing `$('body').toggleClass(localStorage.toggled);` that is in my original question and not in your Fiddle; that preserves the dark/light state on the body class across page reloads. Now it works on my localhost :) We do need your function `updateInterfaceTheme` and the `removeClass` calls, too. – BlueDogRanch Oct 18 '20 at 16:38
  • 1
    @BlueDogRanch Ah you right I forget to add it because it doesn't add any value for the example. Is it fine now? ;) – johannchopin Oct 18 '20 at 16:40
  • 1
    @BlueDogRanch Perfect +1 Please don't forget to activate the bounty :) – johannchopin Oct 18 '20 at 17:05
-1

You should use method getItem().

let x = localStorage.getItem('toggled');

And than make a check for a variable.


https://developer.mozilla.org/ru/docs/Web/API/Storage/getItem

ddd.foster
  • 39
  • 1
  • 6
  • 1
    The [Web Storage API allows for getting and setting of storage items using the dot or bracket syntax (see Basic Concepts)](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API) – Heretic Monkey Oct 15 '20 at 12:13