Unable To Display The Last Visited Date
Following is the script that is meant to store the time,date the user last visited a webpage.But nothing happens when i run the HTML with the script. window.onload = init; functio
Solution 1:
window.onload = function () {
var now = new Date(),
expires = now,
lastVisit = document.cookie.match(/lastVisit=([^;]+)/),
userName = 'somebody';
// 1. You should set month in standalone way
expires.setMonth(now.getMonth() + 2);
// 2. For each cookie you set value individually: for username in 1st line, and for lastVisit in 2nd
document.cookie = "username=" + userName + ";path=/;expires=" + expires.toGMTString();
document.cookie = "lastVisit=" + now.toDateString() + ";path=/;expires=" + expires.toGMTString();
// 3. You should test and extract your cookie value BEFORE you set it (see above with cookie match)
// 4. You should test if it's not null also
if (null != lastVisit) {
// 5. You should use innerHTML property for set content
document.getElementById("lastVisitedOn").innerHTML = lastVisit[1];
}
// 6. But in general you should RTFM more :)
// 7. ps: And also use some standard frameworks for this -- not manual raw JS
}
Solution 2:
Well there are some problems in your code.
As others has mentioned before:
The function "toGMTString()" is deprecated.
Use "toLocaleString()" or "toUTCString()" instead of "toGMTString()" (see also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date#toGMTString)
You should use innerHTML and you had your index wrong.
You cannot use document.cookie that way. Not sure way.
Example:
var now = new Date(); var last = new Date(); var cookieText = "username=" + ";path=/;expires=" + now.setMonth(now.getMonth() + 2).toLocaleString() + ";lastVisit=" + last.toDateString(); document.cookie = cookieText; var lastVisit = cookieText .split("="); document.getElementById("lastVisitedOn").innerHTML = lastVisit[4];
Post a Comment for "Unable To Display The Last Visited Date"