Bootstrap 4 collapsible sidebar, persistence on page reload

Viewed 840

I would like to preface this with saying that english is not my mother tongue, if any of my explanations are vague or don't make sense, please let me know and I will attempt to make them clearer.

I'm playing around with collapsible sidebars (based on a tutorial by Bootstrapious) and I've cobbled together some js (based on this codepen) to save the current toggle state of the sidebar, to keep it persistent between reloads.

var sidebarState = window.localStorage.getItem('sidebarState');

windowWidth = $(window).width();

$(window).resize(function() {
  windowWidth = $(window).width();

    if(sidebarState){
        $('#sidebar').addClass('sidebar-collapsed').removeClass('sidebar-expanded'); 
    }
    else{
        $('#sidebar').addClass('sidebar-expanded').removeClass('sidebar-collapsed'); 
    }
});

$(function() {

    if (sidebarState == "collapsed"){
        $('#sidebar').addClass('sidebar-collapsed').removeClass('sidebar-expanded');
    }
    else{
        if(sidebarState){
        $('#sidebar').addClass('sidebar-collapsed').removeClass('sidebar-expanded'); 
        }
        else{
            $('#sidebar').addClass('sidebar-expanded').removeClass('sidebar-collapsed'); 
        }
    }

    $('#sidebarCollapse').on('click', function(){
        if ( !($('#sidebar').hasClass('sidebar-collapsed')) ) {
            $('#sidebar').addClass('sidebar-collapsed').removeClass('sidebar-expanded');
            window.localStorage.setItem('sidebarState', 'collapsed')
        }
        else{
            $('#sidebar').addClass('sidebar-expanded').removeClass('sidebar-collapsed');
            window.localStorage.removeItem('sidebarState')
        }
        return false;
    });
});

What can I do to hide the transition when the sidebar is collapsed and then the page is reloaded? As it stands right now you'll see the transition from expanded to collapsed, and it makes for a very annoying experience. I tried removing the transition altogether from the stylesheet, but that doesn't make a huge difference. Any help will be greatly appreciated.

Link to codepen: https://codepen.io/anon/pen/eLjwpE

1 Answers

The result is as expected because the DOM is already rendered and you are just making changes to it. You might want to consider switching to React or Vue

Quickfix for your current issue is to have the wrapper initially not displayed until you have retrieved information from the localstorage regarding the collapsed/expanded class assignment then finally using $('.wrapper').css("display", "flex"); to revert back to its nomal display

Codepen: https://codepen.io/anon/pen/PdBMQJ

Related