Question
How can I save the CSS file selected in a <select> element to a browser cookie for approximately one week, then read that cookie the next time the page opens and restore the previously selected stylesheet?
<form>
<label for="myList">Select your CSS layout:</label>
<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>
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);
}
Short Answer
You will learn that browser cookies are small name=value strings, how to give them an expiration date, and how to find one cookie by name. You will also build a CSS theme selector that saves the user’s choice and restores it when the page is loaded again.
Concept
A cookie is a small piece of text that a website asks the browser to store. JavaScript writes a cookie through document.cookie and reads cookies from the same property.
Cookies are not JavaScript variables or objects. The browser exposes them as a semicolon-separated string such as:
Css=style-2.css; sessionId=abc123
To store a selected stylesheet, save its value under a stable name, such as Css:
const cookie = "Css=" + encodeURIComponent("style-2.css");
document.cookie = cookie;
A cookie without an expiration date is usually a session cookie: it is removed when the browser session ends. To keep it for about a week, add an expires attribute with a date in the future, or use max-age.
const oneWeekInSeconds = 7 * 24 * 60 * 60;
document.cookie = "Css=style-2.css; max-age=" + oneWeekInSeconds + "; path=/";
This matters because users expect preferences—such as theme, language, cookie consent, or display density—to remain consistent between visits.
For a simple client-side preference, localStorage is often easier than cookies. Cookies are still useful when the server also needs to receive the value with HTTP requests.
Mental Model
Think of the browser as a hotel desk that stores labelled notes for a website.
- The cookie name is the label:
Css. - The cookie value is the note’s content:
style-2.css. max-ageorexpiresis the note’s discard date.path=/tells the desk that the note is available throughout the site.
When you write document.cookie, you hand the desk one labelled note. When you read document.cookie, the desk gives back all notes that JavaScript is allowed to see. Your code must look through them to find the one labelled Css.
Syntax and Examples
Write a cookie by assigning a correctly formatted string to document.cookie:
const oneWeekInSeconds = 7 * 24 * 60 * 60;
const value = "style-2.css";
document.cookie =
"Css=" + encodeURIComponent(value) +
"; max-age=" + oneWeekInSeconds +
"; path=/; SameSite=Lax";
Important parts:
Css=is the cookie name.encodeURIComponent(value)safely stores characters that could otherwise interfere with cookie syntax.max-ageis measured in seconds.path=/makes the cookie available on every path of the current site.SameSite=Laxis a reasonable default for many same-site preferences.
Read one cookie with a helper function:
function getCookie(name) {
const prefix = name + "=";
const cookies = document.cookie.split(";");
for (const cookie of cookies) {
const item = cookie.trim();
if (item.startsWith(prefix)) {
return decodeURIComponent(item.slice(prefix.length));
}
}
return null;
}
console.log(getCookie("Css")); // "style-2.css" or null
document.cookie contains every readable cookie for the current page, so getCookie splits that string, removes leading spaces, and returns the value belonging to the requested name.
Step by Step Execution
Consider this code after a user selects style-3.css:
const selectedCss = "style-3.css";
const oneWeekInSeconds = 7 * 24 * 60 * 60;
document.cookie =
"Css=" + encodeURIComponent(selectedCss) +
"; max-age=" + oneWeekInSeconds + "; path=/";
-
selectedCssholds the option value:"style-3.css". -
oneWeekInSecondscalculates604800seconds. -
encodeURIComponent(selectedCss)producesstyle-3.css. Encoding does not visibly change this particular value, but it is still a safe habit. -
The browser receives a cookie instruction similar to:
Css=style-3.css; max-age=604800; path=/ -
The browser stores the value under the name
Css. -
On a later page load,
getCookie("Css")searchesdocument.cookieforCss=. -
If found, the program sets the stylesheet link’s
hreftostyle-3.cssand updates the select control to match.
A complete restoration step looks like this:
const savedCss = getCookie("Css");
if (savedCss) {
document.getElementById("css").href = savedCss;
document.getElementById("myList").value = savedCss;
}
Real World Use Cases
Cookies can store small values that should survive a refresh or a later visit:
- Theme preference: light, dark, or high-contrast mode.
- Language selection: remember that a visitor selected
frores. - Cookie-consent state: remember whether a banner has been accepted.
- UI preferences: save compact versus comfortable table density.
- Server-aware preferences: let both browser JavaScript and the server know a user’s locale or theme.
Do not store secrets in JavaScript-readable cookies. Examples include passwords, API keys, and sensitive personal data. A script running on the page can read cookies unless they are created with the HttpOnly attribute, which JavaScript itself cannot set.
Real Codebase Usage
In real projects, cookie code is usually wrapped in small helpers instead of repeatedly parsing document.cookie.
A common preference flow is:
- Read a saved value on startup.
- Validate that it is one of the values the application supports.
- Apply the preference.
- Save a new value whenever the user changes it.
Validation is important. A cookie is external input: users can edit it manually, and old versions of a site may have stored values that are no longer valid.
const allowedThemes = new Set([
"style-1.css",
"style-2.css",
"style-3.css",
"style-4.css"
]);
function applyTheme(theme) {
if (!allowedThemes.has(theme)) {
return;
}
document.getElementById("css").href = theme;
document.getElementById("myList").value = theme;
}
The early return is a guard clause. It prevents an invalid stored value from being applied.
For purely browser-side preferences, many codebases choose localStorage because its API is simpler. Cookies are chosen when the value must also be sent to the server automatically.
Common Mistakes
Saving JavaScript source as text instead of its result
This stores the literal characters document.getElementById(...) rather than the stylesheet URL:
// Incorrect
const cookieString = "Css=document.getElementById(\"css\").href";
Read the value first, then concatenate it:
// Correct
const href = document.getElementById("css").href;
document.cookie = "Css=" + encodeURIComponent(href);
Forgetting the semicolon before cookie attributes
Cookie attributes must be separated from the value:
// Incorrect
"Css=style-1.css expires=Wed, 01 Jan 2030 00:00:00 GMT"
// Correct
"Css=style-1.css; expires=Wed, 01 Jan 2030 00:00:00 GMT"
Using an expiration date in the past
An old date immediately expires the cookie. A date from 2013 will not preserve a current preference. Prefer max-age for a relative duration:
const oneWeek = 7 * 24 * 60 * 60;
document.cookie = "Css=style-1.css; max-age=" + oneWeek + "; path=/";
Assuming document.cookie returns only one cookie
It can return many cookies. Do not compare the whole string directly to one value. Parse it by cookie name with a helper such as getCookie.
Not encoding and decoding values
Values containing spaces, ;, =, or non-ASCII characters can break simple parsing. Use encodeURIComponent when setting and decodeURIComponent when reading.
Forgetting the cookie path
Without path=/, a cookie may only be available under the current directory. Set path=/ when the preference should work across the site.
Testing only with file://
Cookie behavior can be inconsistent when directly opening an HTML file from the filesystem. Test through a local web server, such as a development server or localhost.
Comparisons
| Option | Persists after browser closes? | Sent to the server automatically? | Best fit |
|---|---|---|---|
Cookie with max-age or expires | Yes, until it expires | Yes, for matching requests | Server-readable preferences, sessions managed by server |
| Session cookie | Usually no | Yes, during the session | Temporary server sessions |
localStorage | Yes, until removed | No | Browser-only preferences such as a theme |
sessionStorage | No, cleared when the tab/session ends | No | Temporary per-tab state |
| Cookie expiration attribute | Meaning | Example |
|---|---|---|
max-age | Lifetime in seconds from now | max-age=604800 |
expires | Fixed expiration date in UTC | expires=Wed, 01 Jan 2030 00:00:00 GMT |
For a one-week lifetime, max-age=604800 is often clearer because you do not need to build and format a future date yourself.
Cheat Sheet
// Set a cookie for one week
const week = 7 * 24 * 60 * 60;
document.cookie =
"Css=" + encodeURIComponent("style-2.css") +
"; max-age=" + week + "; path=/; SameSite=Lax";
// Get a named cookie
function getCookie(name) {
const prefix = name + "=";
for (const cookie of document.cookie.split(";")) {
const item = cookie.trim();
if (item.startsWith(prefix)) {
return decodeURIComponent(item.slice(prefix.length));
}
}
return null;
}
// Delete a cookie
function deleteCookie(name) {
document.cookie = name + "=; max-age=0; path=/";
}
- Cookies use
name=value; attribute=valuesyntax. - Separate attributes with semicolons.
- Use
encodeURIComponentanddecodeURIComponentfor values. - Use
max-agein seconds for a duration. - Use
path=/for site-wide availability. - A missing cookie should be handled as
null. - JavaScript cannot create an
HttpOnlycookie. - Never store passwords, tokens, or other secrets in ordinary JavaScript-readable cookies.
FAQ
How do I create a cookie in JavaScript?
Assign a cookie string to document.cookie:
document.cookie = "name=value; max-age=3600; path=/";
How do I read a specific cookie in JavaScript?
document.cookie returns all readable cookies as one string. Split it on ;, find the item beginning with name=, and return its decoded value. A helper function avoids repeating this logic.
Why does my cookie disappear when I close the browser?
You likely created a session cookie. Add max-age or expires to make it persistent.
How long is one week in cookie max-age seconds?
One week is 7 * 24 * 60 * 60, which equals 604800 seconds.
Why is my CSS cookie not available on another page?
The cookie may have been created without the appropriate path. Use path=/ if pages across the site need to read it.
Should I use a cookie or localStorage for a theme preference?
Use localStorage when only browser JavaScript needs the preference. Use a cookie when the server should receive the preference too, for example to render the initial page using the selected theme.
Can JavaScript set a secure HttpOnly cookie?
No. JavaScript can include Secure and SameSite in a cookie it sets, but HttpOnly cookies must be created by the server.
Why should cookie values be encoded?
Cookie syntax uses special characters such as ; and =. Encoding prevents a value containing special characters from being misinterpreted as part of the cookie format.
Mini Project
Description
Build a stylesheet preference switcher for a small website. When a visitor selects a CSS file, the page applies it immediately and stores the choice in a cookie for one week. On a later visit, the page restores the saved choice.
Goal
Create a working CSS theme selector that persists the selected stylesheet in a cookie and restores it on page load.
Requirements
:[
Keep learning
Related questions
Angular ngClass Conditional Class Binding Explained
Learn how to use Angular ngClass for conditional classes, fix common binding mistakes, and understand why this template error happens.
Apply CSS to an iframe: Same-Origin Styling in HTML
Learn why parent-page CSS does not style iframe content, how same-origin rules work, and practical ways to style embedded pages safely.
Apply Multiple CSS Transforms: rotate() and translate()
Learn how to combine multiple CSS transform functions such as rotate() and translate(), understand transform order, and avoid overwritten rules.