Skip to content Skip to sidebar Skip to footer

Load An Ad (div) Just Once On First Load

I wanted to know how can I have a div that has an ad to load or become visible ONLY the first time you load the page but hide it every time the page is refreshed? I only have the c

Solution 1:

Use a cookie:

$(document).ready(function() {
    if (!readCookie("adSeen")) {
        $(".referralProgram").fadeIn("slow");
        createCookie("adSeen", "1", 1000);
    }
});

functioncreateCookie(name, value, days) {
    if (days) {
        var date = newDate();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } elsevar expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

functionreadCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    returnnull;
}

Cookie functions from quirksmode.org.

Edit: Since so many are discussing how to deal with this if cookies are disabled, it should be pointed out that server session implementations rely on either a cookie, or a session identifier in the url. At best, you could only prevent displaying the ad for the same user as long as the session identifier is in the url. Returning to the home page sans session id would re-display the ad. Additionally, a careless implementation (and even some careful implementations) could result in false positives for other users if a user shares a url. localStorage solutions won't work with cookies disabled in most, if not all, browsers.

Solution 2:

You'll need a way to keep track of when an ad has been displayed to the user. Set a cookie when the ad is created and check for it before displaying again?

Solution 3:

You can use client side persistent storage to flag the user has already seen this. Here are 3 options:

1) Cookies - Set a cookie on the visiting users machine.

2) HTML5 Storage - You can store the flag in browser (HTML5 Only) storage.

3) Server Session - If you are using middleware (PHP, ASP.NET, Java, etc.) you can track via a session variable (this is an abstraction of a cookie and is only as persistent as you create it to be).

Solution 4:

I am not sure what your server side implementation is like, but if you are worried about cookies being turned off you could handle this on the server side using session state.

Post a Comment for "Load An Ad (div) Just Once On First Load"