Add cookies to toggle sidebar

白昼怎懂夜的黑 提交于 2019-12-13 02:55:04

问题


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"
        });
    };
});


来源:https://stackoverflow.com/questions/33462473/add-cookies-to-toggle-sidebar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!