Search code examples
javascriptjquerycookiessetcookie

Set cookie only when onclick and hide the message


I'm trying to set up a cookie message on a page. What I want is when the cookie does not exist, the message is displayed. And when the user clicks on "I Accept" button, the cookie is set. And that the message is no longer displayed when user returns to the page/website.

But what it does now is setting the cookie immediately when the user visits the we page.

$(document).ready(function() {


    var visit=GetCookie("AMIR86");
    if (visit==null){
        cookiebar();
    }
    var expire=new Date();
    expire=new Date(expire.getTime()+7776000000);
    document.cookie="AMIR86=here; expires="+expire;


    $('#close-cookies').click(function(){ 
        $('#cookiebar').addClass('close-cookies');
    });

});

function GetCookie(name) {
    var arg=name+"=";
    var arglen=arg.length;
    var dclen=document.cookie.length;
    var i=0;

    while (i<dclen) {
        var j=i+arglen;
            if (document.cookie.substring(i,j)==arg)
                return "here";
                i=document.cookie.indexOf(" ",i)+1;
            if (i==0) 
                break;
    }
    return null;
}

function cookiebar() {
    $('#cookiebar').addClass('display');
}

And my working jsfiddle: http://goo.gl/61aLuS


Solution

  • This chunk of code sets the cookie. For readability and clean coding practice, move it into its own function.

    function setAgreeCookie() {
        var expire=new Date();
        expire=new Date(expire.getTime()+7776000000);
        document.cookie="AMIR86=here; expires="+expire;
    }
    

    Then, set up a click handler on your "I agree" button to set the cookie.

    $('#close-cookies').click(function(){ 
        setAgreeCookie();
        $('#cookiebar').addClass('close-cookies');
    });