Home > Web Front-end > JS Tutorial > How Can I Set and Retrieve Cookies Using JavaScript?

How Can I Set and Retrieve Cookies Using JavaScript?

Susan Sarandon
Release: 2024-12-23 00:12:03
Original
412 people have browsed it

How Can I Set and Retrieve Cookies Using JavaScript?

Setting and Retrieving Cookies with JavaScript

To retain certain preferences or user information across multiple sessions, you may want to utilize cookies. In JavaScript, setting and retrieving cookies is a straightforward task.

Setting a Cookie

To set a cookie with a specific name, value, and expiration time:

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=/";
}
Copy after login

Retrieving a Cookie

To retrieve a cookie by its name:

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;
}
Copy after login

Example Usage

In your HTML file:

<select>
Copy after login

In your JavaScript file:

// Set the cookie when the user selects a CSS file
function setCSSLayout() {
  var cssFile = document.getElementById("myList").value;
  setCookie("cssFile", cssFile, 7);
}

// Get the cookie and set the CSS file accordingly
function getCSSLayout() {
  var cssFile = getCookie("cssFile");
  if (cssFile) {
    document.getElementById("css").href = cssFile;
  }
}

// Load the previously selected CSS file
window.onload = function () {
  getCSSLayout();
};
Copy after login

By utilizing these functions, you can easily set and retrieve cookies in JavaScript, allowing you to store user preferences and enhance your web applications.

The above is the detailed content of How Can I Set and Retrieve Cookies Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template