jmasterx
jmasterx

Reputation: 54113

Storing a value in a cookie in JS?

I have a function that creates a button and toggles a div.

I would like this div to be togled on or off based on a cookie value. the cookie is updated each time this is toggled. The initial value is the cookie value.

If no cookie is present, one is created with initial value of 'true'. The cookie is_side_toggled is a boolean.

function addRightButton() {

    $('.fc-header-right').html
        ('<a class="btn btn-small btn-unscheduled">>></a>');

    if ($('#cal-side').is(":visible")) {
        $('.btn-unscheduled').html('>>');
    }
    else {
        $('.btn-unscheduled').html('<<');
    }

    $('.btn-unscheduled').on('click', function () {

        $('#cal-side').toggle();
        if ($('#cal-side').is(":visible")) {
            $('.btn-unscheduled').html('>>');
        }
        else {
            $('.btn-unscheduled').html('<<');
        }
        resizeCalendar();
    })
}

How could I add a bool cookie and get its value?

Thanks

Upvotes: 0

Views: 89

Answers (2)

gashu
gashu

Reputation: 494

Cookies can be accessed through document.cookie() methood native to JS, if you don;t wish to use a library as jQuery else using jquery, cookies can be accessed/manipulated as here. Please use something like $.cookie('scheduled', true) based on your code

[Edit:] SO didn't show me this ques. is answered and answer above me by @Omar is correct

Upvotes: 0

DiverseAndRemote.com
DiverseAndRemote.com

Reputation: 19888

you could use the jquery cookie plugin at https://github.com/carhartl/jquery-cookie and do something like:

function addRightButton() {

    if($.cookie('scheduled') == '0'){
        $('.fc-header-right').html('<a class="btn btn-small btn-unscheduled"><<</a>');
        $('#cal-side').hide();
    }
    else
        $('.fc-header-right').html('<a class="btn btn-small btn-unscheduled">>></a>');

    if ($('#cal-side').is(":visible")) {
        $('.btn-unscheduled').html('>>');
    }
    else {
        $('.btn-unscheduled').html('<<');
    }

    $('.btn-unscheduled').on('click', function () {

        $('#cal-side').toggle();
        if ($('#cal-side').is(":visible")) {
            $('.btn-unscheduled').html('>>');
            $.cookie('scheduled','1');
        }
        else {
            $('.btn-unscheduled').html('<<');
            $.cookie('scheduled','0');
        }
        resizeCalendar();
    })
}

Upvotes: 1

Related Questions