JavaScript: incrementing a cookie value and printing to the console - javascript

According to Set cookie and get cookie with JavaScript, the canonical function to set a cookie is:
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
I'm trying to modify this function so that it:
a) instantiates a counter variable the first time the page loads
b) increments the counter variable each time the page is refreshed
c) prints the current value of the counter variable to the console
Here is my attempt:
function setCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
else {
expires = "";
}
if (!value) { // should I be checking to see if the COOKIE _itself_ exists? (rather than the value)
var value = 1;
} else {
value++;
}
document.cookie = name + "=" + value + expires + "; path=/";
console.log('Cookie value is', value)
}
### EDIT: ###
Here is a function to get the cookie:
function getCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
EDIT 2
Here is what I'm trying based on one of the suggestions:
function setCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
console.log('Cookie value is', value)
}
function readCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
//setCookie('foo', 3, 5);
//var x = readCookie('foo');
//if (x) {
// console.log('this is foo bar!')
//}
let t = readCookie('foo') || 0;
setCookie('foo', t++, 5);
This results in:
Cookie value is 0
##########################################
Calling setCookie('test', 1, 5) results in:
Cookie value is 2
I get a value of 2 even when loading the page for the first time (presumably because there is a numerical value passed for value when the function is called).
Should I be checking to see if the cookie itself exists (rather than a numerical value for the value argument)?
I would greatly appreciate any assistance with implementing a, b, and c above.
Thanks!

Related

Add a value to a cookie with expiration data?

How can I add a cookie which expires in 2 months to 'test#gmail.com' from the following code
<div id="home">
<div class="name" my-data="123">Email: test#gmail.com</div>
</div>
I think the code for the actual time should be as follows but I do not know how to add the value to it:
function myemail () {
var expiryDate = new Date();
expiryDate.setMonth(expiryDate.getMonth() + 2);
document.cookie = cookieName + '=y; expires=' + expiryDate.toGMTString
Assuming you have privileges to add an ID to your div, the following code works fine
<body>
<div id="home">
<div class="name" my-data="123" id="email-div">Email: test#gmail.com</div>
<button onclick="myemail()">Set it</button>
</div>
<script>
function myemail() {
var expiryDate = new Date();
var email = document.getElementById("email-div").textContent.split("Email:")[1]
expiryDate.setMonth(expiryDate.getMonth() + 2);
document.cookie = 'emailCookie=' + email + ';expires=' + expiryDate.toGMTString() + ';path=/';
}
</script>
</body
Well I have used a button to trigger the action. You can do the same in any event.
toGMTString is a function, you need to call.
Replace expiryDate.toGMTString to expiryDate.toGMTString()
const Cookie = {
get: function (name) {
const nameEq = name + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEq) == 0) {
return c.substring(nameEq.length, c.length);
}
}
return null;
},
set: function (name, value, hours) {
const expires = "";
if (hours) {
let date = new Date();
date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
const expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
};
You can change hours to whatever and of course
this one date.setTime(date.getTime() + (hours * 60 * 60 * 1000)); to the corresponding formula
Usage`
Set: Cookie.set('myemail', 'test#gmail.com', 1460) // 1460 is 2 months in hours
Get: Cookie.get('myemail')
const email = document.getElementsByClassName('name')[0].textContent.split(' ')[1]; Cookie.set('myemail', email, 1460);

saving random picture on the computer / ip

I have a script that draws a random picture after pressing the button.
var imagesArray = ["slonce.gif", "gwiazda.gif", "kochankowie.gif", "wieza.gif"];
function displayImage(){
var num = Math.floor(Math.random() * 4); // 0...6
document.picture.src = imagesArray[num];
}
I want the picture to be remembered for the whole day on the computer or IP that randomized it.
I read about local storage and cookies but I have no idea how I can set the lifetime of this choice.
I created something this and it works
function createCookie(cookieName,cookieValue)
{
var date = new Date();
date.setTime(date.getTime()+(1*24*60*60*1000));
document.cookie = cookieName + "=" + cookieValue + "; expires=" + date.toGMTString();
}
function getCookie(cookieName)
{
var name = cookieName + "=";
var allCookieArray = document.cookie.split(';');
for(var i=0; i<allCookieArray.length; i++)
{
var temp = allCookieArray[i].trim();
if (temp.indexOf(name)==0)
return temp.substring(name.length,temp.length);
}
return "";
}
function checkCookie()
{
var number = getCookie("randomPicture");
if (number!=""){
document.picture.src = imagesArray[number];
}
else
{
var num = Math.floor(Math.random() * 4); // 0...3
document.picture.src = imagesArray[num];
if (num!=null)
{
createCookie("randomPicture", num);
}
}
}
called with the function checkCookie()
One simple option that you have, would be to store a cookie on the computer which expires after one day. Then, at the time the page is loaded you can use JavaScript to check if the cookie is there.
If it is, then you can show the button, otherwise show the picture.
W3Schools covers how to store a cookie and provides a function:
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=/";
}
They also have written a function get a cookie:
function getCookie(cname) {
var name = cname + "=";
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 "";
}

jquery plugin to manage cookies

I have to create, update, delete, get the cookies in my project for different products. So is there any jquery plugin for this. Now i am using this to mange cookies in my project.
function createCookie(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=/";
}
function readCookie(name) {
var nameEQ = name + "=";
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, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
I need a plugin for this which can also update the previous cookie with new product and their value.
There are several plugins for jQuery cookies. You may try https://github.com/carhartl/jquery-cookie or https://plugins.jquery.com/cookie/ or just Google it. and find many other plugins.

Getting value from a cookie

I have set a cookie using the following and it works well. I can see it in browser cookie(console).
But how can i get back the value from cookie ??
days = 1;
cookiename = 'uid';
cookieValue = result.pp.uid;
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 = cookiename + "=" + cookieValue + expires + "; path=/";
I have the following code , but i dont want to use the function.
function readCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
Ive no idea of how they are getting the value of cookie..
Is there a simple way like document.cookie ?
Try this library
https://github.com/carhartl/jquery-cookie
Also see this SO post
How do I set/unset cookie with jQuery?
Example from their docs
Read cookie:
$.cookie('the_cookie'); // => "the_value"
$.cookie('not_existing'); // => undefined

preserving the state using javascript and jquery

I having problem figuring howto preserve the present state ...Let say I have selected radio button and checkbox in present form and navigate way to a different page but if I want to go back to old page how should I able to see the selected radio and checkboxes in my previous page..
Well you can use cookies to do the same. here is a small code snippet that acts over cookies:
var myCookieHandler = (function () {
return {
createCookie: function (name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
},
readCookie: function (name) {
var nameEq = name + "=";
var ca = document.cookie.split(';');
var i;
for (i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') { c = c.substring(1, c.length); }
if (c.indexOf(nameEq) === 0) { return c.substring(nameEq.length, c.length); }
}
return null;
},
deleteCookie: function (name) {
this.createCookie(name, null, -1);
}
};
}());
usage:
myCookieHandler .writeCookie("Login","true",2);
var cookieValue=myCookieHandler.readCookie("Login");
myCookieHandler.deleteCookie("Login");
Thus when you come back to this page you read your cookie and do the necessary with the same.
Hope this helps..

Categories