How to use js-cookie library In Javascript
In this approach, we are using the js-cookie library, which provides a simple way to manage cookies in JavaScript. This library has methods like Cookies.set() and Cookies.get() to easily set and retrieve cookies.
CDN Link:
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/js-cookie/3.0.1/js.cookie.min.js">
</script>
Syntax:
Cookies.set('cookie-name', value);
const cVal = Cookies.get('cookie- name');
Example: The below example uses js-cookie library to set and retrieve cookies using JavaScript.
<!DOCTYPE html>
<head>
<title>Example 2</title>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/js-cookie/3.0.1/js.cookie.min.js">
</script>
</head>
<body>
<h1 style="color: green;">
w3wiki
</h1>
<h3>Using js-cookie library</h3>
<input type="text" id="uInput"
placeholder="Enter cookie value">
<button onclick="setFn()">
Set Cookie
</button>
<button onclick="getFn()">
Get Cookie
</button>
<p id="cVal"></p>
<script>
function setFn() {
const value = document.
getElementById('uInput').value;
Cookies.set('newCookie', value);
alert('Cookie has been set!');
}
function getFn() {
const cVal = Cookies.get('newCookie');
document.getElementById('cVal').textContent =
`Cookie Value: ${cVal}`;
}
</script>
</body>
</html>
Output:
How to Set & Retrieve Cookies using JavaScript ?
In JavaScript, setting and retrieving the cookies is an important task for assessing small pieces of data on a user’s browser. This cookie can be useful for storing user preferences, session information, and many more tasks.
Table of Content
- Using document.cookie
- Using js-cookie library
Contact Us