Armaan Malik Armaan Malik - 5 months ago 19
jQuery Question

Show loading animation only on first time page load using Cookies?

I have loading animation on my HTML page and it is working absolutely fine. The problem is whenever page gets refreshed, the loading animation appears again and I want to limit it to only first time page load.

I was using cookies to solve the problem and I took reference from one of stackoverflow questions:
load an ad (div) just once on first load. I was using the exact same code which is answered there, just replaced my id.

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


Rest of the code is same. My cookies are enable, but it is not working. Help me to fix it.

Here's my code: https://jsfiddle.net/mytest_jsfiddle/ojo2mosd/5/

Answer

Change your code to

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

    function createCookie(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        } else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    function readCookie(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);
        }
        return null;
    }

For reference, Please refer to the below fiddle:

https://jsfiddle.net/aman_chhabra/fguq4hnd/1/

Hope that helps.

Comments