0

I am running the following code which loads a div and hies it according to cookie but does not show it back again once a cookie is set.

I do not understand why this is not running.

<!DOCTYPE html>
<html>

<head></head>

    <body>
    <div style="width:250px;height:250px;background-color:#000;" id="PostShare">
    </div>
    </body>

    <script language="javascript" type="text/javascript" async>
    function createPages(name,value,days) {
       var date = new Date();
       date.setTime(date.getTime()+(days*24*60*60*1000));
       var expires = date.toGMTString();
       document.cookie = name+"="+value+"; expires="+expires+"; path=/";
    }

    function readPages(name) {
        var flag = 0;
        var dcmntPages = document.cookie.split(';');
        for(var i=0;i < dcmntPages.length;i++) {
            var ck = dcmntPages[i];
            while (ck.charAt(0)==' ') {
                ck = ck.substring(1,ck.length);
            }
            if(ck) {
                cparts = ck.split('=');
                if (cparts[0] == name) flag=1;
            }              
        }     
        if(flag) { 
            return true; 
        } else {
            return false; 
        }  
    }

    function checkPages(name) {
        if (readPages(name)) {
    document.getElementById('PostShare').style.display = "none";
    document.getElementById('PostShare').style.visibility = "hidden";
        }
        else {
    document.getElementById('PostShare').style.display = "block";
    document.getElementById('PostShare').style.visibility = "visible";
        createPages(name,"cookie 4 the day",1); 
        }
    }

    checkPages("MyPages");
    </script>
    </body>

</html>

I am trying the same on incognito and so but it does not work. Please help me understand how to make this code work or what should be the code for hiding a div for user on first load and showing it on rest of loads for the day.

Thanks

Tarun Jain
  • 23
  • 5

1 Answers1

0

Your implementation looks good. If your viewing the page in your browser from file, cookies won't set. You need to host it on a server. You can run simple server to host your html file : - python - apache - npm

kewwwa
  • 137
  • 4