Create a JavaScript file visits.js that creates or retrieves a cookie named visi
ID: 3567407 • Letter: C
Question
Create a JavaScript file visits.js that creates or retrieves a cookie named visits that keeps count of the number of times the user has visited the page. You must use the cookie library from chapter 9. Create a visits.html file that displays the number of visits to the site. If it is the first visit you should display "Welcome, this is your first visit" otherwise it should display "Welcome back, you have visited this site x times" (here x would be the actual visit count INCLUDING the current visit). The message must appear on the visits.html page. Do NOT use an alert for this program. You should see the correct count displayed on the visits.html page when you load or reload the page (do NOT use an alert for this message). Test this program in several browsers to make sure that the count is being correctly incremented. Note: it will not work in all browsers.
Explanation / Answer
visits.html
<html>
<head>
<title>Visits</title>
</head>
<body>
<script src="js/visits.js"></script>
<script src="js/coo</p> <p>kies.js"></script>
</body>
</html>
cookies.js
var COOKIE = {
// Function for setting a cookie:
setCookie: function(name, value, expire) {
'use strict';
// Add validation!
// Begin creating the value string:
var str = encodeURIComponent(name) + '=' + encodeURIComponent(value);
// Add the expiration:
str += ';expires=' + expire.toUTCString();
// Create the cookie:
document.cookie = str;
}, // End of setCookie() function.
// Function for retrieving a cookie value:
getCookie: function(name) {
'use strict';
// Useful to know how long the cookie name is:
var len = name.length;
// Split the cookie value:
var cookies = document.cookie.split(';');
// Loop through the values:
for (var i = 0, count = cookies.length; i < count; i++) {
// Lop off an initial space:
var value = (cookies[i].slice(0,1) == ' ') ? cookies[i].slice(1) : cookies[i];
// Decode the value:
value = decodeURIComponent(value);
// Check if this iteration matches the name:
if (value.slice(0,len) == name) {
// Return the part after the equals sign:
return value.split('=')[1];
} // End of IF.
} // End of FOR loop.
// Return false if nothing's been returned yet:
return false;
}, // End of getCookie() function.
// Function for deleting cookies:
deleteCookie: function(name) {
'use strict';
document.cookie = encodeURIComponent(name) + '=;expires=Thu, 01-Jan-1970 00:00:01 GMT';
} // End of deleteCookie() function.
}; // End of COOKIE declaration
visits.js
window.onload = function () {
'use strict';
var visits = COOKIE.getCookie('visits');
if(!visits){
visits = 1;
document.write("Welcome, this is your first visit");
} else {
visits = parseInt(visits) + 1;
document.write("Welcome back, you have visited this site " + visits + " times.");
}
var expire = new Date(); // Today!
expire.setDate(expire.getDate() + 7); // One week!
COOKIE.setCookie('visits', visits, expire);
};