Joshua Joshua - 5 months ago 8
HTML Question

Hiding div based on cookie value when loading the page

I have created a div and used jquery to hide and show the div. When the user click on hide I want to hide the div for 5 minutes till the user loads the page again. I have saved the state (whether hidden or not) in a cookie. When the user is loading the page for the second time within 5 mins the div should be hidden. I have tried the code below and it is not working. Can somebody help me with this?

<script>
$(document).ready(function () {
if (getCookie(hidden) === "yes") {
$("#divAlert").hide();
if ($("#Hide").is(":visible")) {
$("#Hide").css("visibility", "hidden");
}

$("#Show").css("visibility", "visible");
}


$("#Hide").click(function () {
$("#divAlert").hide();
if ($("#Hide").is(":visible")) {
$("#Hide").css("visibility", "hidden");
}
setCookie();
$("#Show").css("visibility", "visible");

});

$("#Show").click(function () {
$("#divAlert").show();

$("#Hide").css("visibility", "visible");


if ($("#Show").is(":visible")) {
$("#Show").css("visibility", "hidden");
}
});
});

function setCookie() {
var currentDate = new Date();
document.cookie = "hidden=yes;exppires=" + currentDate.getMinutes() + 1;
}

function getCookie(cookiename) {
var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');

if (results)
return (unescape(results[2]));
else
return null;
}
</script>

Answer

Assuming your getCookie() and setCookie() functions work properly, this line of your code:

getCookie(hidden);

should be:

getCookie("hidden");

You would have seen this problem immediately if you looked at your javascript error console as this is probably a script error.

The rest of your code can be simplified like this:

    $(document).ready(function () {
        if (getCookie(hidden) === "yes") {
            $("#divAlert").hide();
            $("#Hide").css("visibility", "hidden");
            $("#Show").css("visibility", "visible");
        }


        $("#Hide").click(function () {
            $("#divAlert").hide();
            $(this).css("visibility", "hidden");
            $("#Show").css("visibility", "visible");
            setCookie();

        });

        $("#Show").click(function () {
            $("#divAlert").show();
            $(this).css("visibility", "hidden");
            $("#Hide").css("visibility", "visible");
        });           
    });