Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

I'm trying to set a cookie depending on which CSS file I choose in my HTML. I have a form with a list of options, and different CSS files as values. When I choose a file, it should be saved to a cookie for about a week. The next time you open your HTML file, it should be the previous file you've chosen.

JavaScript code:

function cssLayout() {

    document.getElementById("css").href = this.value;

}

function setCookie(){

    var date = new Date("Februari 10, 2013");

    var dateString = date.toGMTString();

    var cookieString = "Css=document.getElementById("css").href" + dateString;

    document.cookie = cookieString;

}

function getCookie(){

    alert(document.cookie);

}

HTML code:

<form>

    Select your css layout:<br>

    <select id="myList">

        <option value="style-1.css">CSS1</option>

        <option value="style-2.css">CSS2</option>  

        <option value="style-3.css">CSS3</option>

        <option value="style-4.css">CSS4</option>

    </select>

</form>

1 Answer

0 votes
by (40.7k points)

You can try this simple code:

function setCookie(name,value,days) {

    var expires = "";

    if (days) {

        var date = new Date();

        date.setTime(date.getTime() + (days*24*60*60*1000));

        expires = "; expires=" + date.toUTCString();

    }

    document.cookie = name + "=" + (value || "")  + expires + "; path=/";

}

function getCookie(name) {

    var nameEQ = name + "=";

    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,c.length);

        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);

    }

    return null;

}

function eraseCookie(name) {   

    document.cookie = name+'=; Max-Age=-99999999;';  

}

Now, for calling functions try this:

setCookie('ppkcookie','testcookie',7);

var x = getCookie('ppkcookie');

if (x) {

    [do something with x]

}

Have a look this document: http://www.quirksmode.org/js/cookies.html

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...