© Kaily | How to Set, Get and Delete Cookies using Vanilla JavaScript in LayZee UI Blogger Theme. |
In this tutorial, we are going to learn how to SET, GET and DELETE Cookies using Vanilla JavaScript In LayZee UI. We will create functions to reduce our codes and make it easy to do these operations. It will help you in your JavaScript projects.
Getting Started
Follow the following steps to use the codes in your HTML document.
Basic
Add the following JavaScript codes under a
const Cookie = {
get: (e) => { e = document.cookie.match(new RegExp("(?:^|; )" + e.replace(/([.$?*|{}()[\]\\/+^])/g, "$1") + "=([^;]*)")); return e ? decodeURIComponent(e[1]) : void 0 },
set: (e, n, o = {}) => { o = { path: "/", ...o }, o.expires instanceof Date && (o.expires = o.expires.toUTCString()); let c = unescape(encodeURIComponent(e)) + "=" + unescape(encodeURIComponent(n)); for (var t in o) { c += "; " + t; var a = o[t]; !0 !== a && (c += "=" + a) } document.cookie = c },
rem: (e) => { Cookie.set(e, "", { "max-age": -1 }) }
}
Functions
- Cookie
- .set(key, value, [config]) ⇒
void - .get(key) ⇒
Cookie key value - .rem(key) ⇒
void
Cookie.set(key, value, [config]) ⇒ void
To set cookie with desired key and value.
Param | Type | Default | Description |
---|---|---|---|
key | Key of the cookie to set | ||
value | Value of the cookie key | ||
[config] | { path: "/" } | To add "max-age" ( |
Returns:
Example:
<script>
const userDetails = {
name: "Kaily",
email: "noreply@kaily.in"
};
Cookie.set("user", JSON.stringify(userDetails), { secure: true, "max-age": 3600 });
</script>
Cookie.get(key) ⇒ Cookie key value
To get cookie with its key.
Param | Type | Default | Description |
---|---|---|---|
key | Key of the cookie to get |
Returns:
Example:
<script>
const cookieValue = Cookie.get("user");
const userObj = cookieValue != undefined ? JSON.parse(cookieValue) : null;
console.log(userObj);
</script>
Cookie.rem(key) ⇒ void
To remove cookie with its key.
Param | Type | Default | Description |
---|---|---|---|
key | Key of the cookie to remove |
Returns:
Example:
<script>
Cookie.rem("user");
</script>
Credit:
www.kaily.in