Why does my local storage function does not update variable? - javascript

So I was trying to create an incremental game or clicker game or idle game. And everything else is fine, but when it comes to the save and load function it's broken. So my load function works wonderfully, but the problem is that my save function won't save the updated variable, instead, it saves the not updated variable which basically makes the saving and loading pointless.
Code:
function saving() {
localStorage.setItem('save',JSON.stringify(save));
alert("save correctly!");
}
function load() {
var savegame = JSON.parse(localStorage.getItem("save"));
if (typeof savegame.Cookies !== "undefined") cookies = savegame.Cookies;
if (typeof savegame.Cursors !== "undefined") cursors = savegame.Cursors;
if (typeof savegame.Farms !== "undefined") farms = savegame.Farms;
console.log("cookies : ", cookies);
console.log('farms :', farms);
console.log('cursors :', cursors);
}
and I defined the variable "save" as the following.
var save = {
Cookies: cookies,
Cursors: cursors,
Farms: farms
}
and the cookies, cursors, and farms, variables are all set to zero.
After I increment the value in my game, however, the save variable is still using the not incremented variable.
I want it to save the variable like this: 2000 cookies, 30 cursors, 7 farms, instead of all 0.
I am fairly new to js and I've been trying this for the last two days now.
Maybe it's just some ignorant and careless mistake, someone please point it out.

You need to call saving method on every change of the variable save.

Related

Using Localstorage to store and retrieve javascript variables from one html page to another (DOM)

I have one html page 1.html and i want to get some text content and store it to a js.js file using jquery to get the text by id.
This code only works in 1.html page, where the text I want to copy from is but not in 2.html file.
Here is my code. Note that it works if I store text inside localstorage setter second parameter.
$( document ).ready(function() {
var c1Title= $('#r1c1Title').text();
//changing c1Title to any String content like "test" will work
localStorage.setItem("t1",c1Title);
var result = localStorage.getItem("t1");
$("#title1").html(result);
alert(result);
});
Here is the complete demo I am working on Github:
You need to use either localStorage or cookies.
With localStorage
On the first page, use the following code:
localStorage.setItem("variableName", "variableContent")
That sets a localStorage variable of variableName for the domain, with the content variableContent. You can change these names and values to whatever you want, they are just used as an example
On the second page, get the value using the following code:
localStorage.getItem("variableName")
That will return the value stored in variableName, which is variableContent.
Notes
There is a 5MB limit on the amount of data you can store in localStorage.
You can remove items using localStorage.removeItem("variableName").
Depending on where you are, you may need to take a look at the cookie policy (this effects all forms of websites storing data on a computer, not just cookies). This is important, as otherwise using any of these solutions may be illegal.
If you only want to store data until the user closes their browser, you can use sessionStorage instead (just change localStorage to sessionStorage in all instances of your code)
If you want to be able to use the variable value on the server as well, use cookies instead - check out cookies on MDN
For more information on localStorage, check out this article on MDN, or this one on W3Schools
Please try to use this code. It's better to use local storage.
Here you need to make sure that you are setting this local storage
value in parent html page or parent js file.
create local storage
localStorage.setItem("{itemlable}", {itemvalue});
localStorage.setItem("variable1", $('#r1c1Title').text());
localStorage.setItem("variable2", $('#r1c2Title').text());
Get local storage value
localStorage.getItem("{itemlable}")
alert(localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));
For more information follow this link https://www.w3schools.com/html/html5_webstorage.asp
If you wanted to store in div then follow this code.
Html Code
<div class="div_data"></div>
Js code:
$(document).ready(function () {
localStorage.setItem("variable1", "Value 1");
localStorage.setItem("variable2", "Value 2");
$(".div_data").html(' First variable ::: '+localStorage.getItem("variable1") + ' Second variable ::: '+ localStorage.getItem("variable2"));
});
Hope this helps.
You can use local storage as mentioned in above comments. Please find below how to write in javascript.
Local Storage Pros and Cons
Pros:
Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity.
5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain.
This gives you considerably more space to work with than a typical 4KB cookie.
The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
Cons:
It works on same-origin policy. So, data stored will only be available on the same origin.
// Store value in local storage
localStorage.setItem("c1Title", $('#r1c1Title').text());
// Retrieve value in local storage
localStorage.getItem("c1Title");
Your html div
<div id="output"></div>
Add Javascript Code
$('#output').html(localStorage.getItem("c1Title"));
Let me know if it not works
Create a common.js file and modified this and save.
Session = (function () {
var instance;
function init() {
var sessionIdKey = "UserLoggedIn";
return {
// Public methods and variables.
set: function (sessionData) {
window.localStorage.setItem(sessionIdKey, JSON.stringify(sessionData));
return true;
},
get: function () {
var result = null;
try {
result = JSON.parse(window.localStorage.getItem(sessionIdKey));
} catch (e) { }
return result;
}
};
};
return {
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
}
};
}());
function isSessionActive() {
var session = Session.getInstance().get();
if (session != null) {
return true;
}
else {
return false;
}
}
function clearSession() {
window.localStorage.clear();
window.localStorage.removeItem("CampolUserLoggedIn");
window.location.assign("/Account/Login.aspx");
}
Insert like this.
$(function () {
if (!isSessionActive()) {
var obj = {};
obj.ID = 1;
obj.Name = "Neeraj Pathak";
obj.OrganizationID = 1;
obj.Email = "npathak56#gmail.com";
Session.getInstance().set(obj);
}
///clearSession();
});
get like this way
LoggedinUserDetails = Session.getInstance().get();

JavaScript: Like-Counter with Memory

Complete - Edited Once
I am looking to create a Like Counter with persistent Memory!
Right now, my project is stored on a USB-Drive and I'm not thinking of uploading my semi-finished site to the Internet just yet. I'm carrying it around, plugging and working.
A feature of the site, is a Heart Counter and Like Counter, respective with their symbolic icons.
I have a little sideline JavaScript file that has a dozen functions to handle the click-events and such - such as the Number Count of the counters.
But, as the values of the counters are auto-assigned to Temporary Memory - if you were to reload the page - the counter number would reset to it's default, Zero. A huge headache...
Reading from .txt
I thought of using the experimental ReadFile() object to handle the problem - but I soon found that it needed a user-put file to operate (from my examinations).
Here's my attempt:
if (heartCount || likeCount >= 1) {
var reader = new FileReader();
var readerResults = reader.readAsText(heartsAndLikes.txt);
//return readerResults
alert(readerResults);
}
When loaded, the page runs through standard operations, except for the above.
This, in my opinion, would have been the ideal solution...
Reading from Cookies
Cookies now don't seem like an option as it resides on a per-computer basis.
They are stored on the computer's SSD, not in the JavaScript File... sad...
HTML5 Web Storage
Using the new Web Storage will be of big help, probably. But again, it is on a per-computer basis, no matter how beautiful the system is...
localStorage.heartCount = 0 //Originally...
function heartButtonClicked() {
if (localStorage.heartCount) {
localStorage.heartCount = Number(localStorage.heartCount) + 1
}
document.getElementById('heartCountDisplay').innerHTML = localStorage.heartCount
} //Function is tied to the heartCountButton directly via the 'onclick' method
However, I am questioning whether web storage can be carried over on a USB-Drive...
Summarised ideas
Currently, I am looking to Reading and Editing the files, as it's most ideal to my situation. But...
Which would you use? Would you introduce a new method of things?
Please, tell me about it! :)
if (typeof(Storage) !== "undefined") { //make sure local storage is available
if (!localStorage.heartCount) { //if heartCount is not set then set it to zero
localStorage.heartCount = 0;
}
} else {
alert('Local storage is not available');
}
function heartButtonClicked() {
if (localStorage.heartCount) { //if heartCount exists then increment it by one
localStorage.heartCount++;
}
//display the result
document.getElementById('heartCountDisplay').innerHTML = localStorage.heartCount
}
This will only work on a per computer basis and will not persist on your thumb drive. The only way I can think of to persist the data on your drive is to manually download a JSON or text file.

Appending a query string to the url on refresh using javascript

I am trying to read a label and append its value as a query string once the user hits the refresh button on their browser. The code I have so far is:
function AppendQueryString() {
var currUrl = document.location;
var trackingNbr = $("#lblTrackingNbr").text();
if (window.location.href.indexOf("?TrackingNumber=") <= 0 && trackingNbr !== null) {
document.location = currUrl + "?TrackingNumber="+ trackingNbr;
}
}
window.onbeforeunload = AppendQueryString();
The problem is, the trackingNbr variable is always null even though the label has the value before I hit refresh. What am I doing wrong or is there a better way of doing this ?
SessionStorage would be a good solution, with something like this:
sessionStorage.setItem("trackingNbr", trackingNbr);
When the refresh button is clicked, you can pull this value back from session storage easily:
var trackingNbr = sessionStorage.getItem("trackingNbr");
Security: Because this is session storage rather than local storage, the value will be cleared from the browser when the session ends. Note that only your domain can access whatever you put into either session or local storage. However, a knowledgeable end user can read the value by using developer tools in any of the major browsers.

Continual counter regardless of page refresh

I have this piece of jQuery that currently increments a number by one every 5 seconds. The problem I have is that its client side, therefore it resets every time you refresh the page.
Instead I'd like the counter to continue even if you are away from the site and regardless of how many times you refresh the page, which is why I thought a server side script such as PHP would be better suited to my use case. If not please suggest otherwise.
I've setup a working fiddle of what I currently have with jQuery: http://jsfiddle.net/f354bzy5/
What would be the PHP to recreate this affect that include my requirements above?
Here's the Jquery I'm using:
//Counter
var counter = 22000000000;
$(".count").html(counter);
setInterval(function () {
$(".count").html(counter);
++counter;
}, 5000);
Check this DEMO
//Counter
var counter=22000000000;
if(typeof(localStorage.getItem('counts'))!='object')
{
counter=parseInt(localStorage.getItem('counts'));
}
setInterval(function () {
$(".count").html(counter);
++counter;
localStorage.setItem('counts',counter);
}, 1000);
Highlight on localStorage
localStorage is an implementation of the Storage Interface. It stores
data with no expiration date, and gets cleared only through
JavaScript, or clearing the Browser Cache / Locally Stored Data -
unlike cookie expiry.
Can you store counter in cookie.
document.cookie = counter.
so you can get last value from cookie, if user refresh the page.
It comes down to two simple choices for you. Just choose the right one which better fits your requirement:
Choose Cookie : If you want the server side to access the counter. Remember cookies are sent along with the requests by default.
Choose Local Storage : If you don't want to send the counter along with requests every time, you are supposed to go for local storage.
You could do it with localStorage. Here's how I am doing it. You can tweak it as you need.
//detecting support for localStorage.
if (window.localStorage) {
//counterValue already exists in localStorage? Let's use that or set to zero.
var counterValue = localStorage.counterValue || 0;
setInterval(function() {
//increment the counter and store updated vale in localStorage as well.
localStorage.counterValue = ++counterValue;
//put it in your HTML if you might
$(".count").html(counterValue);
}, 5000);
}
How about using localStorage with some utility functions? Bear in mind that this is a client side solution and the item would be wiped off when the user deletes the browser cache/local data etc.
function isLocalStorage() {
try {
return 'localStorage' in window && window['localStorage'] !== null;
} catch(e) {
return false;
}
}
function setCounter(key, val) {
localStorage.setItem(key, val);
}
function getCounter(key) {
return parseInt(localStorage.getItem(key), 10);
}
(function() {
var key = "myCounter";
var counter = isLocalStorage() && getCounter(key) || 1;
var $placeholder = $(".count");
$placeholder.html(counter);
setInterval(function () {
counter++;
$placeholder.html(counter);
isLocalStorage() && setCounter(key, counter);
}, 2000);
}());
-- Demo --

Counter variable does not persist when loading a new page

I want to use counter variable in javascript like static variable with timer. counter must decrease by 1 on every second. I m working on online exam. on answering a question new question comes on the same page. my problem starts when counter variable is initialized with new question(means new page). counter variable does not persists on new page...suggest any solution
<script language="JavaScript">
function ExamTimer()
{
if ( typeof ExamTimer.counter == 'undefined' )
{
ExamTimer.counter = 30000; // 30 min
}
else
{
ExamTimer.counter = ExamTimer.counter-1;
if(ExamTimer.counter<=0)
{
alert("exam finish");
}
setTimeout(ExamTimer, 1000);
}
window.onload=ExamTimer;
</script>
Javascript variables are not meant to outlive the current page load. The browser's Javascript engine executes the code on every page load (though most browsers cache the complied code), so client-side variables are lost whenever the page reloads.
There are several common methods to pass values from one page to another:
DOM storage
Cookies
Server-side variables via a GET or POST request
Whatever method you select, remember it needs to be adequately resilient to unwanted manipulation by the user.
Using ajax pass value from one to another page. use session to hold last remainTime thai is passed to next page
<script language="JavaScript">
function ExamTimer()
{
if ( typeof ExamTimer.counter == 'undefined' )
{
ExamTimer.counter = <cfoutput>#session.RemainTime#</cfoutput>;
}
else
{
ExamTimer.counter = ExamTimer.counter-1;
$.get('linktosend.cfm',{counter:ExamTimer.counter},function(responseText)
{
// value of ExamTimer.counter send to linktosend.cfm and store in session.RemainTime
});
if(ExamTimer.counter<=0)
{
alert("exam finish");
}
setTimeout(ExamTimer, 1000);
}
window.onload=ExamTimer;
</script>

Categories

Resources