Reputation: 35
I'm a bit stuck on some javascript. So the script below sets eith one of two cookies.
If the page contains 'lpt' and a cookie called organic doesn't exist (not sure if the second part actually works) then create a cookie. Otherwise create a different one.
Problem is which ever cookie is created needs to be held and not swap them out? ie if the first one is created don't ever create the other one.
if(document.URL.indexOf("lpt") >= 0 && document.cookie.indexOf("organic") < 0){
document.cookie = "ppc_campaign=this will be the url; expires=Thu, 18 Dec 2018 12:00:00 UTC; path=/";
}
else {
document.cookie = "organic=this will be the url; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";
}
Upvotes: 2
Views: 2960
Reputation: 3922
may be this function will help you to find your cookie in easiest way just passing your name of cookie... you can modify according to your logic
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
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 "";
}
function checkCookie(cookiename) {
var user = getCookie(cookiename);//cookiename="username"
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
Upvotes: 0
Reputation: 134
You dont want to dublicate the cooke if it is already created
set expiry date for almost 10years, 2050 or 2030 Then use this function to find if cookie already exists
document.cookie.search('cookie')
if this function returns -1 then save your cookie
Upvotes: 1