Search code examples
javascriptjqueryhtmlcookiessetcookie

Set a cookie for 1 hour and check for it on load


I want to do a little animation when an user visits the site but I don't want it to show every time the user switches between the subpages. At the moment it does the animation every time and I don't know why.

Here is my code:

$(document).ready(function() {
    "use strict";
    if (document.cookie.indexOf('visited') > -1) {
        // They've been here before.
        alert("hello again");
    }
    else {
        // set a new cookie
        var d = new Date();
        d.setTime(d.getTime() + (3600 * 1000));
        document.cookie = "visited=yes;" + "expires=" + d.toUTCString() + ";path=/";
        // slide in navbar
        sleep(100);
        document.getElementById("navlist").style.left = "63%";
    }
});

Solution

  • You can simple use sessionStorage instead of cookies like so:

    $(document).ready(function(){
      if(sessionStorage.getItem("visitedBefore") == undefined){
                sessionStorage.setItem("visitedBefore", "1");
                alert("Welcome for the first time!");
        }
    });
    

    Here is the JSFiddle demo