Javascript for cookies

 Cookies are small text files stored in the user's browser by a website. They are used to store data such as user preferences, login information, and shopping cart contents. In JavaScript, cookies can be created, read, and deleted using the document.cookie property.

Here's an example of how to create a cookie in JavaScript:

javascript
function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; }

This function sets a cookie named cname with the value cvalue that expires in exdays days.

Here's an example of how to read a cookie in JavaScript:

javascript
function getCookie(cname) { var name = cname + "="; var ca = document.cookie.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 ""; }

This function returns the value of the cookie named cname.

Here's an example of how to delete a cookie in JavaScript:

javascript
function deleteCookie(cname) { document.cookie = cname + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; }

This function deletes the cookie named cname by setting its expiration date to a time in the past.

In conclusion, cookies can be created, read, and deleted in JavaScript using the document.cookie property. The examples provided above show how to set, read, and delete cookies in JavaScript.

Javascript for cookies


Post a Comment

Previous Post Next Post