Add cookies to toggle sidebar

2019-08-26 09:22发布

问题:

I have a toggling sidebar on my side, and now I want to use cookies to make it remember what state it's at. This has been brought up a lot before, but I haven't been able to find a solution that works with my code. (Or maybe it does, but I'm really new at this, I could just have used it wrong.)

var main = function() {
    $('.icon-menu').click(function() {
        $('.menu').animate({
            left: "0px"
        }, 200);

        $('body').animate({
            left: "240px"
        }, 200);
    });

    $('.icon-close').click(function() {
        $('.menu').animate({
            left: "-240px"
        }, 200);

        $('body').animate({
            left: "0px"
        }, 200);

    });
};

I looked into this ask, it seems to be what I'm looking for, but the codes where so different I didn't get it to work. Same with enter link description here Viktor's helpful setup here - would it be easier to just redo the code with something more "standard"? Or can I set up an if command for both the menu and the body?

Grateful for all tips. Cheers!

回答1:

Download and include js-cookie, and use it as follows:

$(document).ready(function() {
    $('.icon-menu').click(function() {
        $('.menu').animate({
            left: "0px"
        }, 200);

        $('body').animate({
            left: "240px"
        }, 200);

        Cookies.set('menu-state', 'open');
    });

    $('.icon-close').click(function() {
        $('.menu').animate({
            left: "-240px"
        }, 200);

        $('body').animate({
            left: "0px"
        }, 200);

        Cookies.set('menu-state', 'closed');
    });

    // Open menu (without animation) if it was open last time
    if (Cookies.get('menu-state') === 'open') {
        $('.menu').css({
            left: "0px"
        });

        $('body').css({
            left: "240px"
        });
    } else {
        $('.menu').css({
            left: "-240px"
        });

        $('body').css({
            left: "0px"
        });
    };
});