Add, Edit, Delete Cookies with JavaScript
There are many ways to communicate and store data from front-end to back-end, but many require AJAX which may take too much time to develop or might not fit the project correctly. A neat alternative to save data and be able to access that data from the server is using browser cookies. Cookies can be created and destroyed by javascript, and while the syntax can be confusing, I’ve gathered this little script that will make it easier to use:
/* COOKIES OBJECT */ var Cookies = { // Initialize by splitting the array of Cookies init: function () { var allCookies = document.cookie.split('; '); for (var i=0;i<allCookies.length;i++) { var cookiePair = allCookies[i].split('='); this[cookiePair[0]] = cookiePair[1]; } }, // Create Function: Pass name of cookie, value, and days to expire create: function (name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; this[name] = value; }, // Erase cookie by name erase: function (name) { this.create(name,'',-1); this[name] = undefined; } }; Cookies.init();
Unfortunately, there’s no easy way to simple update a cookie (correct me if I’m wrong) but this will allow you to delete and re-create as needed:
// Erase cookie "test" Cookies.erase('test'); // Recreate cookie "test" with a new value of "cookievalue" and set to expire in 10 days Cookies.create('test','cookievalue',10)
