I’m trying to implement a feature using a JavaScript set cookie to save the selected CSS file based on options in my HTML. When I choose a CSS file, it should be saved in a cookie for about a week. The next time I open my HTML file, it should remember the previously selected CSS file.
Here’s my JavaScript code:
function cssLayout() {
document.getElementById("css").href = this.value;
}
function setCookie() {
var date = new Date();
date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // Set cookie to expire in a week
var expires = "expires=" + date.toUTCString();
var cookieString = "Css=" + document.getElementById("css").href + ";" + expires + ";path=/"; // Correct cookie format
document.cookie = cookieString; // Save cookie
}
function getCookie() {
alert(document.cookie); // Retrieve and display cookies
}
How can I properly set and retrieve a cookie using JavaScript to remember the selected CSS file?
Hello All! Hope all are doing well,
Here’s a short and straightforward implementation:
javascript
Copy code
// Function to set the CSS and save it as a cookie
function cssLayout() {
var selectedCSS = this.value;
document.getElementById("css").href = selectedCSS;
setCookie(selectedCSS); // Save selected CSS in cookie
}
// Set cookie to expire in 7 days
function setCookie(value) {
var date = new Date();
date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
document.cookie = "Css=" + value + ";expires=" + date.toUTCString() + ";path=/";
}
// Retrieve cookie value
function getCookie() {
var name = "Css=";
var cookieArray = decodeURIComponent(document.cookie).split(';');
for (var i = 0; i < cookieArray.length; i++) {
var cookie = cookieArray[i].trim();
if (cookie.indexOf(name) == 0) return cookie.substring(name.length);
}
return "";
}
// Apply saved CSS on page load
function loadCSSFromCookie() {
var savedCSS = getCookie();
if (savedCSS) document.getElementById("css").href = savedCSS;
}
window.onload = loadCSSFromCookie;
This code saves the selected CSS in a cookie and applies it on page load.
Hello Jasminepuno,
To achieve this, you can attach an event listener to the dropdown or input field that sets the cookie when a new CSS file is selected. Here’s an example of how to do it:
// Attach event listener to dropdown/select input
document.getElementById("cssSelector").addEventListener("change", function() {
cssLayout.call(this); // Use the selected value in the function
});
This will trigger the cssLayout
function whenever a new option is selected from the dropdown.