saving random picture on the computer / ip - javascript

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 "";
}

Related

JavaScript: incrementing a cookie value and printing to the console

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!

Set cookie with array() in jquery

I would like to be able to check if a cookie (id) is set or not: if not set, then create it. If set, retrieve the value (= an array). How can I retrieve the array from the cookie?
I hear that I would have to use JSON, but I'm not sure how that would work with the following code?
function start(id){
if (document.cookie.indexOf('id') === -1 ) {
setCookie('id', id, 7);
}
else {
var playedID = [GET COOKIE ARRAY]
playedID.push(id);
setCookie('id',playedID);
}
}
Here's a way to do it based on some helper functions to make sure you are parsing and stringifying the cookie correctly.
getCookie and setCookie are from https://www.w3schools.com/js/js_cookies.asp
// This won't run due to security policies on this site, but you can run it in the dev tools and see.
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 "";
}
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=/";
}
function getCookieArray(cname) {
var cookie = getCookie(cname);
return cookie ? JSON.parse(cookie) : [];
}
function pushToCookieArray(cname, cvalue, exdays) {
var cookieArray = getCookieArray(cname);
cookieArray.push(cvalue);
setCookie(cname, JSON.stringify(cookieArray), exdays);
}
function start(id) {
pushToCookieArray('id', id, 7);
console.log(getCookieArray('id'));
}
start(5);
start(6);
start(8);
First a cookie is not stored as an array but a string : if you type document.cookie in you console, you will get all the cookies from the website you are visiting, separated with a coma.
So as explained here : https://www.w3schools.com/js/js_cookies.asp,
you will have to create a custom function to access the cookie you need.
Then the value of you cookie is still a string, so as explained here if you want to save an array of ids, you have to use JSON.stringify to encode you array as a string : I want to store Javascript array as a Cookie
You can then create it or update its value :
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 "";
}
function setCookie(cname, cvalue) {
document.cookie = cname + "=" + cvalue + ";";
}
function start(id){
if (getCookie('id') === '' ) {
setCookie('id', JSON.stringify([+id]));
}
else {
let ids = JSON.parse(getCookie('id'))
console.log(ids)
ids.push(+id);
setCookie('id', JSON.stringify(ids));
}
}
function sendID(id) {
console.log(document.getElementById("user-id").value)
start(id);
alert(getCookie("id"))
}
Here is a working example : https://codepen.io/adrientiburce/pen/ExVbYWy?editors=1010

Create cookie Javascript

I have to create a JS cookie when a user click a button, this cookie will remember him after 10 minutes with another popup.
Example:
<button>Click me!</button>
and the button will hide when user click, after 10 minutes the button will show again:
<button>Click me!</button>
Script part:
function setCookieMsg(name) {
var d = new Date();
var time = d.setTime(d.getTime() + (600000));
document.cookie = name + "=" + time;
}
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) != -1) return c.substring(name.length, c.length);
}
return "";
}
function checkCookieMsg() {
var cookie = getCookie("name");
var d = new Date() - 600000;
if (cookie == "") {
setCookie("name", cookie);
}else if (d => cookie) {
$().getUnReadMessage();
}
}
What I've wrong?
You didn't mention the expires in cookie. The expires date should be UTC time string.
function setCookieMsg(name) {
var date = new Date();
date.setTime(date.getTime()+(600000));
var expires = "; expires="+date.toUTCString();
document.cookie = name + "=" + expires;
}

how to store on click appended html in to client side cookies

I am trying to append some data on run time..
now I have to store this appended data into client side Cookies.
Any suggestion much appreciated. Thanks in advance.
here is the code and fiddle URL:
$('#add').on('click', function(){
var inputHTML = $('#inputName').val();
$('<li>'+inputHTML+'</li>').appendTo('#inputBox > ul');
});
http://jsfiddle.net/ft26u/12/
You can use localStorage, like this:
$('#add').on('click', function(){
var inputHTML = $('#inputName').val();
$('<li>'+inputHTML+'</li>').appendTo('#inputBox > ul');
var myData = localStorage.cookieData ? JSON.parse(localStorage.cookieData) : new Array();
myData.push(inputHTML);
localStorage.cookieData = JSON.stringify(myData);
console.log(myData);
})
Use these functions:
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = escape(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 unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
Edit Updated sample to load cookie on load
http://jsfiddle.net/aZXMr/3/

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