Phil
Phil

Reputation: 1453

How to Create Cookies to Remember a Javascript Instruction

John Giotta kindly gave me this code earlier (on stack overflow) in order to implement a "turn off styles" button on my website (for a university assignment).

function nostyle() {
    for (i=0; i<document.styleSheets.length; i++) {
        void(document.styleSheets.item(i).disabled=true);
    }
} 

I was wondering how easy it would be to implement a cookie to remember that this javascript has been applied so that every page navigated after on the site has styles turned off (My knowledge is extremely basic, I am only a first year).

Regards

Upvotes: 2

Views: 1446

Answers (1)

John Giotta
John Giotta

Reputation: 16934

function SetCookie(cookieName,cookieValue,nDays) {
    var today = new Date();
    var expire = new Date();
    if (nDays==null || nDays==0) nDays=1;
    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie = cookieName+"="+escape(cookieValue)
        + ";expires="+expire.toGMTString();
}

Set your css_disabled cookie

SetCookie('css_disabled', 'true', 100);

To read the cookie:

function ReadCookie(cookieName) {
    var theCookie=""+document.cookie;
    var ind=theCookie.indexOf(cookieName+"=");
    if (ind==-1 || cookieName=="") return "";
    var ind1=theCookie.indexOf(";",ind);
    if (ind1==-1) ind1=theCookie.length; 
    return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

if (ReadCookie('css_disabled') == 'true') {...

Upvotes: 3

Related Questions