Heli
Heli

Reputation: 45

Setting and Checking cookies with javascript

I have a script that set a cookies once a link is clicked and then when when u visited the page again it will check the cookies and alert that you are already here. However my code doesn't seem to work. Can any1 help out??

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
    <title></title>
    <script type="text/javascript">
        function get_cookie("visited"){
            if (document.cookie.indexOf("visited") >= 0) {
                // They've been here before.
                alert("hello again");
            }
    </script>

</head>

<body onload="get_cookie()">

    <script type="text/javascript">
        /*  This function sets the cookie   */
        function iLoveCookies() {
                days = 30; // number of days to keep the cookie
                myDate = new Date();
                myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = 'cookieName=visited; expires=' + myDate.toGMTString();
            }
            /*  end of cookie function  */


        
    </script>

    <a href="#" onclick="iLoveCookies()">Set Cookie</a>
</body>
</html>

Upvotes: 0

Views: 86

Answers (1)

Jason Cust
Jason Cust

Reputation: 10899

It looks like you basically had typos causing the errors. You might want to use a linter to check your JavaScript or at the least look at your browser's developer console to see what it's telling you.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
    <title></title>
    <script type="text/javascript">
        function get_cookie(){
            if (document.cookie.indexOf("visited") >= 0) {
                // They've been here before.
                alert("hello again");
            }
          }
    </script>
  

</head>

<body onload="get_cookie()">

    <script type="text/javascript">
        /*  This function sets the cookie   */
        function iLoveCookies() {
                days = 30; // number of days to keep the cookie
                myDate = new Date();
                myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = 'cookieName=visited; expires=' + myDate.toGMTString();
            }
            /*  end of cookie function  */
    </script>

    <a href="#" onclick="iLoveCookies()">Set Cookie</a>
    <a href="#" onclick="get_cookie()">Get Cookie</a>
</body>
</html>

Upvotes: 2

Related Questions