A tiny (< 1kb) helper library that makes working with cookies a bit easier.
Vanilla JS Pocket Guides or join the Vanilla JS Academy and level-up as a web developer.
Want to learn how to write your own vanilla JS libraries? Check out my
Compiled and production-ready code can be found in the
dist directory. The
src directory contains development code.
You can also use the jsDelivr CDN. I recommend linking to a specific version number or version range to prevent major updates from breaking your site. Jar uses semantic versioning.
<!-- Always get the latest version --> <!-- Not recommended for production sites! --> <script src="https://cdn.jsdelivr.net/gh/cferdinandi/jar/dist/jar.min.js"></script> <!-- Get minor updates and patch fixes within a major version --> <script src="https://cdn.jsdelivr.net/gh/cferdinandi/jar@1/dist/jar.min.js"></script> <!-- Get patch fixes within a minor version --> <script src="https://firstname.lastname@example.org/dist/jar.min.js"></script> <!-- Get a specific version --> <script src="https://email@example.com/dist/jar.min.js"></script>
Create a cookie.
Pass in the cookie name and value as arguments. As an optional third argument, provide the amount of time (in milliseconds) before the cookie expires
// Create a cookie named `sandwich` with a value of `turkey` jar.set('sandwich', 'turkey'); // Create a cookie named `drink` with a value of `soda` that expires in a day jar.set('drink', 'soda', 1000 * 60 * 60 * 24);
Here are some common expiration values.
var hour = 1000 * 60 * 60; var day = 1000 * 60 * 60 * 24; var week = 1000 * 60 * 60 * 24 * 7; var year = 1000 * 60 * 60 * 24 * 7 * 365;
Get the value of a cookie. Pass in the cookie name as an argument.
// Get the `sandwich` cookie jar.get('sandwich');
Delete a cookie. Pass in the cookie name as an argument.
// Delete the `sandwich` cookie jar.remove('sandwich');
Working with the Source Files
If you would prefer, you can work with the development code in the
src directory using the included Gulp build system. This compiles, lints, and minifies code.
Make sure these are installed first.
- In bash/terminal/command line,
cdinto your project directory.
npm installto install required files.
- When it's done installing, run one of the task runners to get going:
gulpmanually compiles files.
gulp watchautomatically compiles files when changes are made and applies changes using LiveReload.
Jar works in all modern browsers, and IE 6 and above.
The code is available under the MIT License.