'Check if user has alread visited site in browser session

So I have this splash screen animation that plays when you visit my website. However, I only want the animation to play the first time you visit it (in the session of course). I tried to make an if else where I check for a cookie called "Session", and if it exists, delete the div containing the animation. If there is no such cookie, create it.

Code:

function session() {
    if (document.cookie.indexOf("visited") >= 0) {
        $('.splash').remove(this);
    } else {
        document.cookie = "visited";
    }
}

I have never used cookies before so I think I might have made some errors



Solution 1:[1]

The portion of your code that deals with cookies should work.

Your problem exists on this line:

$('.splash').remove(this);

Remove this, as it's not necessary.

That line should look like:

$('.splash').remove();

Hope that helps.

Solution 2:[2]

Chrome has a security restriction that doesn't allow you to access cookies unless the page is running from a web server. Firefox will work without a web server with cookies. For quick testing of local files I suggest using http-server.

I use the below cookie functions to set cookies easily. The original code comes from w3cschools site with some modifications for IE8 cookie problems.

setCookie = function (c_name,value,exdays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var expires = exdate.toUTCString();
    var isIE8 = (document.documentMode !== undefined);
    if (exdays == 0) {
        expires = (isIE8 == true) ? "" : "0";
    }
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+expires);
    document.cookie=c_name + "=" + c_value;
}

getCookie = function(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
}

deleteCookie = function(name) {
  document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

To check a cookie you could do:

if (getCookie('visited')) {
    $('.splash').remove();
    deleteCookie('visited');
} else {
    setCookie('visited','true',999); //999 days expiration
}

Solution 3:[3]

An alternative method:

if (sessionStorage.getItem(‘visited’) !== true){
//code that executed if it is user’s first time
sessionStorage.setItem(‘visited’,true);
}else{
//code that executes if it user has already visited
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tyler Biscoe
Solution 2 mbokil
Solution 3 SCRIPTNINJA