Advertisement
RokiAdhytama

Cookie - Chapter 12-1

Jul 4th, 2022
637
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. <html xmlns = "http://www.w3.org/1999/xhtml">
  3.    <head>
  4.       <title>Using Cookies</title>
  5.  
  6.       <script type = "text/javascript">
  7.          <!--
  8.          var now = new Date(); // current date and time
  9.          var hour = now.getHours(); // current hour (0-23)
  10.          var name;
  11.  
  12.          if ( hour < 12 ) // determine whether it is morning
  13.             document.write( "<h1>Good Morning, " );
  14.          else
  15.          {
  16.             hour = hour - 12; // convert from 24 hour clock to PM time
  17.  
  18.             // determine whether it is afternoon or evening            
  19.             if ( hour < 6 )
  20.                document.write( "<h1>Good Afternoon, " );
  21.             else
  22.                document.write( "<h1>Good Evening, " );
  23.          }
  24.  
  25.          // determine whether there is a cookie
  26.          if ( document.cookie )
  27.          {
  28.             // convert escape characters in the cookie string to their
  29.                // english notation
  30.             var myCookie = unescape( document.cookie );
  31.            
  32.                // split the cookie into tokens using = as delimiter
  33.             var cookieTokens = myCookie.split( "=" );
  34.  
  35.             // set name to the part of the cookie that follows the = sign
  36.             name = cookieTokens[ 1 ];
  37.          }
  38.          else
  39.          {
  40.             // if there was no cookie then ask the user to input a name
  41.             name = window.prompt( "Please enter your name", "GalAnt" );
  42.  
  43.                // escape non-alphanumeric characters in the name string
  44.                // and add name to the cookie
  45.             document.cookie = "name=" + escape( name );
  46.          }
  47.  
  48.          document.writeln(
  49.             name + ", welcome to JavaScript programming! </h1>" );
  50.          document.writeln( "<a href= \" JavaScript:wrongPerson() \" > " +
  51.             "Click here if you are not " + name + "</a>" );
  52.  
  53.          // reset the document's cookie if wrong person
  54.          function wrongPerson()
  55.          {
  56.             // reset the cookie
  57.             document.cookie= "name=null;" +
  58.                " expires=Thu, 01-Jan-95 00:00:01 GMT";
  59.  
  60.             // after removing the cookie reload the page to get a new name
  61.             location.reload();
  62.          }
  63.  
  64.          // -->
  65.       </script>
  66.    </head>
  67.  
  68.    <body>
  69.       <p>Click Refresh (or Reload) to run the script again</p>
  70.    </body>
  71. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement