My name is Clayton McIlrath and I am an entrepreneur currently living in CO. I personally enjoy the process of learning, exploring, and doing all things creative as well as sharing my experiences with others. Being an entrepreneur and business owner, I hope that my experiences may help someone else start their own venture and find success and freedom as I have! Feel free to contact me anytime for questions or opportunities.

close
more

»

«


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)
Bookmark and Share

One Response to “Add, Edit, Delete Cookies with JavaScript”

  1. pendekar says:

    thanks. I really needed something like this

Leave a Reply

close