Hai Tien
Hai Tien

Reputation: 3117

How to remember show and hide div with cookie

I have HTML like :

<div id='mainleft-content'>content is visible</div>
<div id="expand-hidden">Button Expand +</div>

And I use Jquery to show/hide div like :

 $(document).ready(function () {
    $("#expand-hidden").click(function () {
        $("#mainleft-content").toggle();
    });
});

I want use cookie to remember the state of div is hide or show of visitors' manipulate.

How can I do it? Thank for your help.

See JSFIDDLE

Upvotes: 3

Views: 9798

Answers (3)

Kirill
Kirill

Reputation: 534

You can use plugin: https://github.com/carhartl/jquery-cookie

and just set states like

$.cookie("visible", 1);

Upvotes: 1

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28528

Here is working fiddle

You may use is(":visible") for this purpose, it will return you whether div is visible or not:

if ( $("#mainleft-content").is(":visible") ){
   alert('its visible');
}
else{
   alert('div is hidden');
}

if you still need the cookies, you may add a function:

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

and set the cookie:

$(document).ready(function () {
    $("#expand-hidden").click(function () {
        $("#mainleft-content").toggle();
        SetCookie("DivStateVisible", $("#mainleft-content").is(":visible"),5);
    });
});

with jQuery using jquery-cookie:

function setCookie(c_name, value, exdays) {
    $.cookie(c_name, value, { expires : exdays });
}

function getCookie(c_name) {
    return $.cookie(c_name);
}

Upvotes: 4

Sergey
Sergey

Reputation: 5207

Using http://plugins.jquery.com/cookie/

$(document).ready(function () {
    $("#mainleft-content").toggle(!!$.cookie("visible"));
    $("#expand-hidden").click(function () {
        $("#mainleft-content").toggle(function() { 
             $.cookie("visible", $("#mainleft-content").is(':visible') ? 1 : 0);
        });
    });
});

Upvotes: 2

Related Questions