set and check a cookie using js cookie

this library makes setting and checking cookies so easy its amazing!

include this script

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.1.4/js.cookie.min.js"></script>

set a cookie

this will add a cookie with the name mycookie and the value hi there

Cookies.set('mycookie', 'hi there'); 

load a cookie

Cookies.get('mycookie');

check if a cookie matches a value

if(Cookies.get('mycookie') !== 'hi there') {
	// cookie content does not match 
} else {
	// cookie content matches the string
}

delete the cookie

Cookies.remove('mycookie');

demo

Note: you will need to check your browser cookies to see the cookie. In chrome you can see this with developer tools: F12. Then find the Applicatoin tab, and then Storage, Cookies for this domain, you should be able to see a cookie named 'moo'.

To see if its persistant (which it should be) reload this page and the cookie should still be there.

demo code

<p><button class='btn btn-primary' onclick="Cookies.set('moo', 'cow');">Set Cookie: 'moo' to 'cow'</button> <button class='btn btn-red' onclick="Cookies.remove('moo');">Delete the moo Cookie</button></p>

Links

JS Cookie Github

Demo

Other Items in js
Page Views

This page has been viewed 116 times.

Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

❤👩‍💻🕹