localStorage doesn't work for all of the elements

I have a code which every time i click the button it changes the background color of different elements by toggling classes and all these are stored in localStorage. But there is a class of one of my elements that it is stored in localStorage but when i refresh the page the new background color is gone, but the value “the new class” is stored. So while all the rest of the elements have the new backgrounds this has the old. I don’t know why this is happening because it is the same code for all the elements. This shouldn’t happen. The element that i am targeting to add class is the “.ps-stream” and the var that i store the localStorage is the “getFavStreamPost” Here is the code:

jQuery(document).ready(function($) {
  if (typeof(localStorage) == 'undefined') {
    alert("Your browser does not support HTML5 localStorage. Try upgrading.")
  } else {
    if (localStorage.getItem("fav") != null && localStorage.getItem("toolbar") != null &&
      localStorage.getItem("makePost") != null && localStorage.getItem("typeOfPost") != null &&
      localStorage.getItem('streamFilter') != null && localStorage.getItem('streamPost') != null) {
      getFav = localStorage.fav;
      getFavTool = localStorage.toolbar;
      getFavMakePost = localStorage.makePost;
      getFavPostType = localStorage.typeOfPost;
      getFavStreamFilter = localStorage.streamFilter;
      getFavStreamPost = localStorage.streamPost;



      $(".widget--box").addClass('widget-darkmode');
      $(".ps-toolbar").addClass('toolbar-darkMode');
      $(".ps-postbox-content").addClass('postBox');
      $(".ps-postbox-tab").addClass('post-type');
      $(".ps-stream__filters").addClass('darkStreamFilter');
      $(".ps-stream").addClass('activityPost');

    }
  }



  button.on('click', function() {


    getFav = localStorage.fav;
    getFavTool = localStorage.toolbar;
    getFavMakePost = localStorage.makePost;
    getFavPostType = localStorage.typeOfPost;
    getFavStreamFilter = localStorage.streamFilter;
    getFavStreamPost = localStorage.streamPost;


    $(".widget--box").toggleClass('widget-darkmode');
    $(".ps-toolbar").toggleClass('toolbar-darkMode');
    $(".ps-postbox-content").toggleClass('postBox');
    $(".ps-postbox-tab").toggleClass('post-type');
    $(".ps-stream__filters").toggleClass('darkStreamFilter');
    $(".ps-stream").toggleClass('activityPost');



    if ($(".widget--box").hasClass('widget-darkmode') && $(".ps-toolbar").hasClass('toolbar-darkMode') &&
      $(".ps-postbox-content").hasClass('postBox') && $(".ps-postbox-tab").hasClass('post-type') &&
      $(".ps-stream__filters").hasClass('darkStreamFilter') && $(".ps-stream").hasClass('activityPost')) {
      localStorage.setItem('fav', 'widget-darkmode');
      localStorage.setItem('toolbar', 'toolbar-darkMode');
      localStorage.setItem('makePost', 'postBox');
      localStorage.setItem('typeOfPost', 'post-type');
      localStorage.setItem('streamFilter', 'darkStreamFilter');
      localStorage.setItem('streamPost', 'activityPost');


    } else {
      localStorage.removeItem('fav');
      localStorage.removeItem('toolbar');
      localStorage.removeItem('makePost');
      localStorage.removeItem('typeOfPost');
      localStorage.removeItem('streamFilter');
      localStorage.removeItem('streamPost');

    }

  });



}); 

so where in your code are those words? Javascript wont invent words to put into your storage, so they must exist (or have existed) in your code.

I am sorry but , by the value “the new class” i was refering to the new class of the element which is the “acitivityPost”. In the localStorage of the browser there is the key: streamPost and the value: activityPost along with the rest of the key value pairs, after i had clicked the button to change the background colors. But when i refresh the page the color of the specific element returns to the original color but the key value pair is still in the memory. That’s why i don’t understand why it doesn’t keep the new background color. The above colde works for all the html elements except for one.

Is this page online somewhere that it can be viewed?

You can visit it by clicking this address: hollovibe.com. It is still in development. It is a local community. Log in: username: user, password: user1234. As you can see from the photo

the problem is in the red boxes in the activity stream. After i changed the colors by clicking the “dark mode” link in the menu bar everything changed to black and when i refreshed the page all remained black except the activity posts, but the value of the new class is still in the memory as you can see.

right. So the bit you’re trying to change is dynamically loaded, which is why jquery isnt finding it when you execute the script. Those boxes dont exist at the moment your script runs.

Couple of options there… change the script that loads the post feed to check and use the localstorage variable as its class, run the script only after the posts have successfully been loaded, or attempt to use javascript to modify the CSS rule on the actual classes.

Thanks, that sounds a good idea. I will try to modify the css rule on the actual classes.

Update: for anyone who has the same problem here is code which works fine now.

jQuery(document).ready(function($){
 $(window).on("load", function() {
        setTimeout(function() {
        
if (typeof(localStorage) == 'undefined') {
    alert("Your browser does not support HTML5 localStorage. Try upgrading.")
  } else {
    if (localStorage.getItem("favBody") != null && localStorage.getItem("favHeader") != null 
        && localStorage.getItem("fav") != null && localStorage.getItem("toolbar") != null &&
      localStorage.getItem("makePost") != null && localStorage.getItem("typeOfPost") != null &&
      localStorage.getItem('streamFilter') != null && localStorage.getItem('streamPost') != null 
       && localStorage.getItem('toggleIcon') != null) {
      getFavBody = localStorage.favBody;
       getFavHeader = localStorage.favHeader; 
      getFav = localStorage.fav;
      getFavTool = localStorage.toolbar;
      getFavMakePost = localStorage.makePost;
      getFavPostType = localStorage.typeOfPost;
      getFavStreamFilter = localStorage.streamFilter;
      getFavStreamPost = localStorage.streamPost;
        getFavToggleIcon = localStorage.toggleIcon;
        
       
        
      $('#body').addClass('nightmode');
        $('.header').addClass('headerNightmode');
      $(".widget--box").addClass('widget-darkmode');
      $(".ps-toolbar").addClass('toolbar-darkMode');
      $(".ps-postbox-content").addClass('postBox');
      $(".ps-postbox-tab").addClass('post-type');
      $(".ps-stream__filters").addClass('darkStreamFilter');
      $(".ps-stream").addClass('activityPost');
        $(".ps-media-grid-item").addClass('activityPost');
        $(".gc-icon-bars").addClass('iconToggle');

    }
  }

     var button = $('.menu-item-178 a');
     //var container = $('#custom-body').toggleClass(window.localStorage.toggled);
     //var containerHeader = $('#custom-header').toggleClass(window.localStorage.toggledHeader);
    


    /* Write your Public custom_public jQuery here! */
    button.on('click', function (event) {
       event.preventDefault();  
    
        

        getFavBody = localStorage.favBody;
        getFavHeader = localStorage.favHeader; 
        getFav = localStorage.fav;
    getFavTool = localStorage.toolbar;
    getFavMakePost = localStorage.makePost;
    getFavPostType = localStorage.typeOfPost;
    getFavStreamFilter = localStorage.streamFilter;
    getFavStreamPost = localStorage.streamPost;
        getFavToggleIcon = localStorage.toggleIcon;
        

    $('#body').toggleClass('nightmode');
        $('.header').toggleClass('headerNightmode');
    $(".widget--box").toggleClass('widget-darkmode');
    $(".ps-toolbar").toggleClass('toolbar-darkMode');
    $(".ps-postbox-content").toggleClass('postBox');
    $(".ps-postbox-tab").toggleClass('post-type');
    $(".ps-stream__filters").toggleClass('darkStreamFilter');
    $(".ps-stream").toggleClass('activityPost');
         $(".ps-media-grid-item").toggleClass('activityPost');
        $(".gc-icon-bars").toggleClass('iconToggle');



    if ($("#body").hasClass('nightmode') && $(".header").hasClass('headerNightmode') && $(".widget--box").hasClass('widget-darkmode') && $(".ps-toolbar").hasClass('toolbar-darkMode') &&
      $(".ps-postbox-content").hasClass('postBox') && $(".ps-postbox-tab").hasClass('post-type') &&
      $(".ps-stream__filters").hasClass('darkStreamFilter') && $(".ps-stream").hasClass('activityPost') 
       && $(".ps-media-grid-item").hasClass('activityPost') && $(".gc-icon-bars").hasClass('iconToggle')) {
      localStorage.setItem('favBody', 'nightmode');
        localStorage.setItem('favHeader', 'headerNightmode');
      localStorage.setItem('fav', 'widget-darkmode');
      localStorage.setItem('toolbar', 'toolbar-darkMode');
      localStorage.setItem('makePost', 'postBox');
      localStorage.setItem('typeOfPost', 'post-type');
      localStorage.setItem('streamFilter', 'darkStreamFilter');
      localStorage.setItem('streamPost', 'activityPost');
        localStorage.setItem('toggleIcon', 'iconToggle');
       


    } else {
      localStorage.removeItem('favBody'); 
        localStorage.removeItem('favHeader');
      localStorage.removeItem('fav');
      localStorage.removeItem('toolbar');
      localStorage.removeItem('makePost');
      localStorage.removeItem('typeOfPost');
      localStorage.removeItem('streamFilter');
      localStorage.removeItem('streamPost');
        localStorage.removeItem('iconToggle');

    }
        
    });
            

            
            var target = $( "#ps-activitystream")[0];
            //var target2 = $( ".custom-activity");
            
            var mutationObserver = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
      var newNodes = mutation.addedNodes; // DOM NodeList
      if( newNodes !== null ) { // If there are new nodes added
    	var $nodes = $( newNodes ); // jQuery set
    	$nodes.each(function() {
    		var $node = $( this );
    		if( $node.hasClass( "ps-stream") || $node.hasClass(".ps-media-grid-item")) {
    			// do something
                console.log(mutation);
                if (localStorage.getItem('streamPost') != null) {
                    getFavStream = localStorage.favStream;
                    
                    $(".ps-stream").addClass('activityPost');
                    $(".ps-media-grid-item").addClass('activityPost');
                } else {
                    $(".ps-stream").removeClass('activityPost');
                     $(".ps-media-grid-item").removeClass('activityPost');
                }
                
                //var button2 = $('.menu-item-178 a');
                
                  
       				
                      
               
    		}
    	});
    }
    
  });
});

// Starts listening for changes in the root HTML element of the page.
mutationObserver.observe(target, {
  attributes: true,
  characterData: true,
  childList: true,
  
});
            
        
        }, 500);
    
    });
    
}); // document ready

I just had to run the script after all the other scripts as m_hutley suggested above and for the activity posts that are loaded when the user scrolls down, i had to use the mutationObserver to track when a specific class appears in the DOM add also the class from the localStorage.

Hello m_hutley, above i posted the working code. But i checked it again it seems that it has stopped adding values to the local storage. Any ideas why this has happened? The code was working fine.
Thank you

well i’m not sure why you’re stacking a setTimeout inside a window.load, inside a document.ready, but… sure…
I’d be absolutely guessing without being able to recreate it myself, but at a guess, your button has changed classes.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.