Lazy cookie?

I am probably beign lazy here… I want the page to display differently if the a cookie has been set.


	   if(document.cookie.indexOf('yesCookie')>0){$("#Mars,#Vers").toggleClass("hide");}
//other code
			x=$("#QQ :radio:checked").val();
			if (x=="yes"){
				$("#Mars,#Vers").toggleClass("hide");
				nd=new Date();
				nd.setDate(nd.getDate()+50);
				document.cookie="yesCookie=yes!; expires="+nd.toUTCString();
			}


Using Safari browsers prefs, I can see that ‘yesCookie’ has been set and has an expiration date of 50 days (as desired), however my if(document.cookie.indexOf(‘yesCookie’)>0){} is always false? Trying to check by doing alert (document.cookie) I get a blank(NULL) response.

I thought since the page only has one cookie and its nature is essentially boolean that ic could check if it was there by doing an idexOf? Is that not possible or did I miss some other detail?

As always I appreciate all input.

If it’s the first cookie then its index at the very start of the string will be zero.
indexOf gives -1 when something isn’t found, so check to see if the index is greater than -1

You could also use these cookie handling functions


function createCookie(name, value, days) {
    var expires = '',
        date = new Date();
    if (days) {
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = '; expires=' + date.toGMTString();
    }
    document.cookie = name + '=' + value + expires + '; path=/';
}
 
function readCookie(name) {
    var nameEQ = name + '=',
        allCookies = document.cookie.split(';'),
        i,
        cookie;
    for (i = 0; i < allCookies.length; i += 1) {
        cookie = allCookies[i];
        while (cookie.charAt(0) === ' ') {
            cookie = cookie.substring(1, cookie.length);
        }
        if (cookie.indexOf(nameEQ) === 0) {
            return cookie.substring(nameEQ.length, cookie.length);
        }
    }
    return null;
}
 
function eraseCookie(name) {
    createCookie(name, '', -1);
}

That way you could check for readCookie(‘yesCookie’) instead, and set it using createCookie(‘yesCookie’, ‘yes!’, 50)


if(readCookie('yesCookie')) {
    ...
}
//other code
x = $("#QQ :radio:checked").val();
if (x === "yes") {
    $("#Mars,#Vers").toggleClass("hide");
    createCookie('yesCookie', 'yes!', 50);
}

lol… JUST caught that, and was coming back to remove the post… but I guess you were quicker. I have a few cookie handling routines I have coded , which I usually use… but since it was only one cookie… with a “yes” or NULL value… I wondered about cutting that corner.

Everything is working now … thanks…:slight_smile: