SolvedAdminLTE How to remember the toggle state of the sidebar menu?

I am using AdminLTE in combination with Codeigniter3. Therefore a lot of HTML is generated on the back-end of my application. I'd like to find a way to let the back-end know the toggle state (collapsed or open) of the sidebar menu so that I can generate the appropriate HTML for a page.

I tried to use the href in:
<a href="<?= site_url("site/toggle");?>" class="sidebar-toggle" data-toggle="offcanvas" role="button">
but that doesn't work because the href is not used.

Does anyone know a way to achieve this?

25 Answers

βœ”οΈAccepted Answer

I've fixed the external Script, with this is your 1. question answered :) i missed this on exporting it from my app.js

to the 2. question, thats a bit complicated, that would need a new CI Controller with 3 functions (2 create cookie + get created cookie/state) and you would need to switch in the JS the cookie based functions with $.post or $.get to get/send data to the CI Controller.

$.AdminLTESidebarTweak = {};

$.AdminLTESidebarTweak.options = {
    EnableRemember: true,
    NoTransitionAfterReload: false
    //Removes the transition after page reload.
};

$(function () {
    "use strict";

    $("body").on("collapsed.pushMenu", function(){
        if($.AdminLTESidebarTweak.options.EnableRemember){
            document.cookie = "toggleState=closed";
        } 
    });
    $("body").on("expanded.pushMenu", function(){
        if($.AdminLTESidebarTweak.options.EnableRemember){
            document.cookie = "toggleState=opened";
        } 
    });

    if($.AdminLTESidebarTweak.options.EnableRemember){
        var re = new RegExp('toggleState' + "=([^;]+)");
        var value = re.exec(document.cookie);
        var toggleState = (value != null) ? unescape(value[1]) : null;
        if(toggleState == 'closed'){
            if($.AdminLTESidebarTweak.options.NoTransitionAfterReload){
                $("body").addClass('sidebar-collapse hold-transition').delay(100).queue(function(){
                    $(this).removeClass('hold-transition'); 
                });
            }else{
                $("body").addClass('sidebar-collapse');
            }
        }
    } 
});

Other Answers:

Thanks @REJack for your script, works nicely!

I adapted it slightly so it uses localStorage. One of the advantages of this approach is that it remembers the state for all pages, whereas the cookie would be set per path. Basically this means the toggle state was remembered on a per page basis (at least in my browser, Chrome 61 on Windows 10), which may be ideal for some uses cases but not mine.

I also tried to reproduce the bug @kher09 mentioned, without much luck. Maybe someone else can chip in there.

    $.AdminLTESidebarTweak = {};

    $.AdminLTESidebarTweak.options = {
            EnableRemember: true,
            NoTransitionAfterReload: true
            //Removes the transition after page reload.
    };

    $(function () {
        "use strict";

        $("body").on("collapsed.pushMenu", function() {
            if($.AdminLTESidebarTweak.options.EnableRemember) {
                localStorage.setItem("toggleState", "closed");
            }
        });
            
        $("body").on("expanded.pushMenu", function() {
                if($.AdminLTESidebarTweak.options.EnableRemember) {
                    localStorage.setItem("toggleState", "opened");
                } 
        });

        if ($.AdminLTESidebarTweak.options.EnableRemember) {
            var toggleState = localStorage.getItem("toggleState");
            if (toggleState == 'closed'){
                if ($.AdminLTESidebarTweak.options.NoTransitionAfterReload) {
                    $("body").addClass('sidebar-collapse hold-transition').delay(100).queue(function() {
                        $(this).removeClass('hold-transition');
                    });
                } else {
                    $("body").addClass('sidebar-collapse');
                }
            }
        }
    });

Hi,
do not use cookies. It's easier to use LocalStorage. I did it here.

  • Store sidebar state
<script type="text/javascript">
    (function ($) {
        /* Store sidebar state */
        $('.sidebar-toggle').click(function(event) {
            event.preventDefault();
            if (Boolean(localStorage.getItem('sidebar-toggle-collapsed'))) {
                localStorage.setItem('sidebar-toggle-collapsed', '');
             } else {
                localStorage.setItem('sidebar-toggle-collapsed', '1');
             }
         });
    })(jQuery);
</script>
  • Recover sidebar state
<script type="text/javascript">
    /* Recover sidebar state */
     (function () {
        if (Boolean(localStorage.getItem('sidebar-toggle-collapsed'))) {
            var body = document.getElementsByTagName('body')[0];
            body.className = body.className + ' sidebar-collapse';
        }
    })();
</script>

This works perfectly for me.

Thanks.

simply use cookies

This is my solution:

JS

$.AdminLTESidebarTweak = {};

$.AdminLTESidebarTweak.options = {
    EnableRemember: true,
    NoTransitionAfterReload: false
    //Removes the transition after page reload.
};

$(function () {
    "use strict";

    function setCookie(value) {
        let name = 'toggleState';
        let days = 365;
        let d = new Date;
        d.setTime(d.getTime() + 24 * 60 * 60 * 1000 * days);
        document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
    }

    $("body").on("collapsed.pushMenu", function () {
        if ($.AdminLTESidebarTweak.options.EnableRemember) {
            setCookie('closed');
        }
    }).on("expanded.pushMenu", function () {
        if ($.AdminLTESidebarTweak.options.EnableRemember) {
            setCookie('opened');
        }
    });
});

PHP (/resources/views/vendor/adminlte/master.blade.php)

<body class="hold-transition @yield('body_class') @if (Cookie::get('toggleState') === 'closed') {{ 'sidebar-collapse' }} @endif">

Laravel Cookies Middleware

<?php

namespace App\Http\Middleware;

use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;

class EncryptCookies extends Middleware
{
    /**
     * The names of the cookies that should not be encrypted.
     *
     * @var array
     */
    protected $except = [
        'toggleState',
    ];
}

Related Issues:

44
AdminLTE Active menu item with multi level submenus
nice script but it is not valid where you took the class ul.level-1 from? πŸ˜„ AdminLTE doesn't use so...
28
AdminLTE Sidebar menu treeview not working after redirection in Angular 4
This problem in Angular 6 and AdminLTE 3 was solved as follows: Note: I have a Sidebar component tha...
13
AdminLTE How to remember the toggle state of the sidebar menu?
I've fixed the external Script with this is your 1 question answered :) i missed this on exporting i...
288
ngx admin No PostCSS Config found with build:prod
Or you can create a file named postcss.config.js in root directory Just leave it empty or write the ...
66
react admin Error: Invariant failed: You should not use <Route> outside a <Router>
Just remember: Before using {Route} from 'react-router-dom' library just make sure you put <Route> i...
59
EasyAdminBundle Multiple file/images upload - OneupUploaderBundle
I got this to work with VichUploaderBundle Is there any possibility to manage upload multiple files?...
58
react admin ra-data-graphql-simple shows error when plugged to apollo-server
I also encountered the issue and actually that's not a bug of React Admin but a React Hook misuse :)...
39
ngx admin Add JWT automatically for every HTTP request
FYI if you are using this solution check out my other reply: #1375 (comment) I couldn't get this to ...
34
react admin display array with arrayField or other
I cannot comprehend why this has been essentially wontfixed There is nothing at all strange about an...
29
CRUD [Feature] Ability to define any (nested) fields inside "table" field
I did something very similar to this implemented a field following the table field default and creat...
27
laravel filemanager Error when accessing /laravel-filemanager
In lfmhelpers.php line 335 replace the return with this: and in vendor/unisharp/laravel-filemanager/...
25
coreui free react admin template Deploy build to Nginx give error Uncaught SyntaxError: Unexpected token <
@thangnvse try this adding this into your nginx conf Step: npm run-script build Copy built files to ...
24
react admin Deprecated findDOMNode warning in StrictMode - originating from react-transition-group
Any timeline on this issue? We are using react-admin for an admin panel for our client and want to e...
16
CRUD How to customize search query?
:-)) hi @nathanielks Glad to hear the package gave was a nice surprise to you Well ...
14
CRUD Concatenate two columns in list view
Here's what you can do to make your attribute show when enableAjaxTable() is present on your CRUD: A...
12
EasyAdminBundle Is there anything new to use translatable entities?
While preparing to upgrade to SF4 and Flex I had a go at this: Integrating KnpLabs/DoctrineBehaviors...
12
CRUD ReflectionException Class translator does not exist
It seems this has to do with calling trans() in config files which is apparently not possible in lar...
12
react admin Typescript declarations
Thanks I'll start writing types for next and post them in DefinitelyTyped Hi ...
12
react admin Pagination fails with *TypeError: onChangePage is not a function*
I think I found a workaround for the time being Using yarn in my package.json I added this resolutio...
11
react admin [RFC] Embedded Arrays using FieldArray
Nice! I think this could make it to the core But I'd prefer that subrecords are displayed as lines r...
7
CRUD Pagination using AJAX
Hi guys I've just finished AJAX pagination Is this considered? Right now all rows are queried ...
5
Serenity Sum of column in Detail Dialog - Shown/calculated immediately in a field of Parent Dialog
Here is a sample for you for OrderDialog constructor: Replace Q.notifySuccess with form.MyField.valu...
4
CRUD Bug image field, store in fake field (store as base64, not path)
Hi everyone Allow me to post this to this closed topic It could be useful to someone Looking for a s...
4
CRUD Laravel Backpack FIlter Not Called
Thx that solved the problem for me: Solution (working for Laravel >= 5.5) Configure App\Http\Middlew...
4
ant design pro πŸ›[BUG] Login doesn't work properly if /api/currentUser route is protected
I can also confirm that I've been hit by this It's much simpler to reproduce also ...
4
Serenity How to implement TreeView by SlickGrid in Serenity
It took me an hour to figure out how to turn default EntityGrid (generated by sergen) to a Tree List...
3
EasyAdminBundle After manual deleting cache got error
Hello Hours debugging helps figure out what's going on How to reproduce: Step 1 Install profiler ...
3
CRUD Upload field type on edit required issue
I know this is a closed issue but I found this after searching for a solution for a similar issue I ...
3
CRUD Return with Validator errors
Hi @OSDDQD This has happened to me before for custom CRUD entities when I applied the web middleware...
3
Serenity Back to use of AD credentials
@Solabar sorry I didn't get a chance to update this Some dudes here have resolved their issues and w...
3
Serenity [Please Comment] Inquiry about switching to TypeScript
Here is some update and proof of concept for TypeScript / Saltaralle interop: In ts-experiments bran...
11
administrate How can I create a new Dashboard without a model?
Is there a plan to implement official support for this? Having pages in dashboards that are NOT dire...
5
administrate A new release to support 5.1.1
@ThisIsMissEm looks like there is an unreleased a commit that solves that issue: 396a31d should be o...
36
crudbooster Hanging on install
I also had the same problem I confirmed that my database setting was in my .env file and my terminal...
9
laratrust Where to create roles and permissions?
I think you could figure it out by trial and error but nevertheless I will do my best to explain it ...
5
crudbooster Image upload?
Here's the magic: CB uses symlinks to mirror files to the public folder Does the image upload work c...
275
ngx bootstrap fix(tooltip): tooltip flickering when hover the mouse on the border on the tooltip position
Add pointer-events: none; to the tooltip css problem solved! .tooltip { pointer-events: none; } ...
174
bootstrap vue Dynamic property for v-b-toggle
v-b-toggle does accept a dynamic value to specify a single target ID Not do not include the # as it ...
147
ng bootstrap No provider for NgbActiveModal! => "Components as content"
try to provide NgbActiveModal on app.module Bug description: When trying to implement the Modal usin...
111
bootstrap vue How to hide OK or Cancel buttons on Modal?
Add property in b-modal component hide-footer=true Hi In the docs it says: You can customize the siz...
101
bootstrap Navbar .sticky-top doesn't work
My setup: Bootstrap@4.0.0-beta.2 macOS Sierra - Version 10.12.6 Google Chrome - Version 62.0.3202.62...
83
ngx bootstrap How to pass data to modal ngx-bootstrap and receive return data ?
here is how you send information back to parent component ( calling component) create a EventEmitter...
73
react bootstrap Fix arbitrary prop passthrough to DOM nodes.
Wait how are library component authors supposed to fix this? Are we supposed to apply the whitelist ...
70
bootstrap vue How to use event row-clicked <b-table>.
Hi guys I'm trying to use event row-clicked to fill some props when click on a b-table row Tried to ...
70
bootstrap Responsive Card Decks
I've managed to find a way of having cards in the responsive system while having equal heights just ...
54
bootstrap Bootstrap dropdown require Popper.js (https://popper.js.org)
For laravel projects using laravel mix window.Popper = require('popper.js').default; does the trick ...
54
bootstrap table-responsive class does not take full width
simple solution use a wrapping <div> with the table-responsive class. This was previously reported i...
51
ngx bootstrap Auto open modal from components
Use ngAfterViewInit instead of ngOnInit The ViewChildis still undefined when the component is initia...
48
reactstrap Reactstrap and React-router 4.0.0-beta.6 - active <NavLink>
The simplest answer is that you can't use reactstrap navlink active prop when passing in react-route...