Karl Karl - 7 months ago 8
Javascript Question

Show Div Every xHours or xDays

Two things I'm having trouble with.

I've constructed a notice that slides in when the page loads and slides out after a set amount of time.

Firstly, I don't want it to run every time the page loads because this would annoy the members. Could this be done with cookies? If so, how?

Secondly, I'd like to make the

<div>
slide out when the user clicks the close button so they don't have to wait for the script to finish.

Answer

I have modified your existing jsFiddle with a basic example of how cookies could be used to record if a user has already seen the popup: http://jsfiddle.net/Jk2AG/27/

$(document).ready(function() {

    if (getCookie("show-slide") == null) {
        $("#dimBackgrnd").hide().delay(1000).fadeIn("slow");

        $("#slide").hide().delay(2000).show("drop", {
            direction: "up"
        }, 500);


        $("#dimBackgrnd").hide().delay(7500).fadeOut("slow");

        $("#slide").delay(6000).hide("drop", {
            direction: "down"
        }, 500);

        setCookie("show-slide", "false", 7);
    }
    else {
        $("#dimBackgrnd").hide();
        $("#slide").hide();
    }

});

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