Skip to content Skip to sidebar Skip to footer

Add Cookies To Toggle Sidebar

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

Post a Comment for "Add Cookies To Toggle Sidebar"