Skip to content
← Back to Community
JavaScript Cookie Functions: 1.0
Profile icon
josef24

To add the cookie functions, first create cookies.js and copy paste this code:

function addCookie(name, value, days) { var dt = new Date; dt.setTime(dt.getTime() + (days*24*60*60*1000)); var expires = "expires="+ dt.toUTCString(); document.cookie = name + "=" + value + ";" + expires + ";path=/"; console.log("Sucessfully created cookie " + name); } function getCookie(name) { var cname = name + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } function checkCookie(name) { var username = getCookie(name); if (username != "") { alert("Welcome again " + username); } else { username = prompt("Please enter your name:", ""); if (username != "" && username != null) { addCookie(name, "user", 365); } } } function deleteCookie(name) { var expires = -1 var dt = new Date; dt.setTime(dt.getTime() + (expires*24*60*60*1000)); var expires = "expires="+ dt.toUTCString(); document.cookie = name + "=" + 0 + ";" + expires + ";path=/"; console.log("Sucessfully deleted cookie " + name); } function changeAndRenewCookie(name, value, expires) { addCookie(name, value, expires) }

Then in html copy paste this:

<script src="cookies.js"></script>

You are free to modify the code, but if you post the modifed code, link to this post.
The repl below will explain:

Voters
Profile icon
KanzariIheb
Profile icon
frissyn
Profile icon
seanlnge
Profile icon
josef24
Comments
hotnewtop
Profile icon
RealAwesomeSam

ReferenceError: setCookie is not defined
at checkCookie (/cookies.js:30:8)
at /script.js:4:1

Profile icon
DynamicSquid

I'm confused, what does this do?

Profile icon
josef24

@DynamicSquid
It enables you to create, delete, and check cookies.

Profile icon
DynamicSquid

@josef24 ooooooooh, web cookies. I though you were talking about actual cookies lol