JavaScript - Store and increase number even after refreshing page - javascript

This JavaScript code is supposed to increase the number
<script type="text/javascript">
var number = 100035;
function increment()
{
number = Math.floor(Math.random() * 500) + number;
showNumber(number);
}
function showNumber(num)
{
document.getElementById("displayDiv").innerHTML = "€" + num;
}
window.onload = function()
{
setInterval("increment()", 1000);
showNumber(number);
}
</script>
<div id="displayDiv"></div>
I must be able to display the last generated number when users refresh the page and when users return to the website. However, the number does not continue from the last generated number and instead starts over.
How can I get this to work?

I try to avoid using intervals so I use setTimeout here, instead.
<script type="text/javascript">
var number = checkCookie();
var daysBeforeExpiration = 365;
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;
}
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 "";
}
function checkCookie() {
var number = getCookie("number");
if (number == "") {
number = "100035"
setCookie("number", number, daysBeforeExpiration);
}
return parseInt(number);
}
function showNumber(num)
{
document.getElementById("displayDiv").innerHTML = "€" + num;
}
incrementInterval = function() {
showNumber(number);
number = Math.floor(Math.random() * 100) + number;
setCookie("number", number.toString(), daysBeforeExpiration)
setTimeout(incrementInterval, 1000);
};
window.onload = function () {
incrementInterval();
};
</script>

Related

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

Redirect to page if cookie is not found

If a cookie for example
visited
was not found, is it possible to make the page redirect to
/welcome
I have started off with this:
function getCookie(visited) {
var dc = document.cookie;
var prefix = visited + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("visited");
if (myCookie == null) {
window.location.href = '/welcome';
}
else {
}
}
Have I done this correctly becuase it is not working correctly on my website.
Try PHP:
if (!isset($_COOKIE['visited'])) {
header("Location: page.php");
}
Try using this checkCookie function below
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 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 checkCookie() {
var visited = getCookie("visited");
if (visited != "") {
// do whatever
} else {
setCookie("visited", "true", 30);
window.location.href = '/welcome';
}
}
For more information, I suggesting visiting W3Schools or MDN

Is it possible to link values between multiple web pages?

I have created a html/css website with different pages, it is a menu and I would like to add checkboxes which add up the total of what they wish to order. As all other aspects of the menu are separate I would like this to be separate so I have created another page and assigned values to each check box and the total works when its on the same page nut not when on different, is there any way to overcome this?
This is the code:
<script type="text/javascript">
function checkTotal() {
document.listForm.total.value = '';
var sum = 0;
for (i=0;i<document.listForm.choice.length;i++) {
if (document.listForm.choice[i].checked) {
sum = sum + parseInt(document.listForm.choice[i].value);
}
}
document.listForm.total.value = sum;
}
</script>
<input type="checkbox" name="choice" value="8.99" onchange="checkTotal()"/>£8.99<br/>
on another page
<p>The Total Of The Order is: <input type="text" size="2" name="total" value="0"/>
Please help and if it isn't obvious I am a beginner
I would use a cookie. The following code from How do I set/unset cookie with jQuery?.
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);
}
Then in your code something like the following
function checkTotal() {
erase("checkBoxes");
var sum = 0;
for (i=0;i<parseInt(readCookie("checkBoxes"));i++) {
if (document.listForm.choice[i].checked) {
sum = sum + parseInt(document.listForm.choice[i].value);
}
}
createCookie("checkBoxes",sum,5);
}

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