Reputation: 1362
I have a home page with a choice of 2 links. When one of those links is clicked I want to create a cookie so that all other internal pages remember this choice.
How do I set a cookie on one page and read the same cookie on different pages?
This is what I have:
// Home page on click event
function setRed() {
document.cookie = "color=red; max-age=" + 60 * 60 * 24 * 365; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 365 days.
};
//Internal Page Check
window.onload = checkCookie();
function checkCookie() {
if (document.cookie.indexOf("color") == "red") {
document.body.id = "red";
} else {
document.body.id = "blue";
};
};
Upvotes: 0
Views: 80
Reputation: 612
Try adding path to your cookie so that all page within your site can access it.
// Home page on click event
function setRed() {
// 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 365 days.
document.cookie = "color=red; max-age=" + 60 * 60 * 24 * 365 +"; path=/";
};
//Internal Page Check
window.onload = checkCookie();
function checkCookie() {
if (document.cookie.indexOf("color") == "red") {
document.body.id = "red";
} else {
document.body.id = "blue";
};
};
Upvotes: 1
Reputation: 1371
Please check out this stackoverflow question.
Basically, when you say document.cookie
make sure to add this to the end of it:
;path=/
Then call checkCookie()
This basically tells the browser to let the cookie be accessed anywhere across the site. However, as far as I know, if your two pages are hosted on different domains it is impossible for both of them to access the same cookie (due to security reasons.)
Also, the function you use to get the cookie looks incorrect. From w3schools:
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
You could then use this function in your checkCookie()
function:
function checkCookie() {
if (getCookie("color") == "red") {
document.body.id = "red";
} else {
document.body.id = "blue";
};
};
Upvotes: 2