Counter Variable saved after web page refresh - javascript

I'm trying to get the counter variable saved when the page refreshes. For example, if the counter is at 5,000 then after refresh the counter will start back up at 5,000 and keeps saving so it doesn't start at the default value.
var count = 309000000;
function tick(){
count += Math.round(Math.random()*3);
$('#test').text(count.toLocaleString());
count;
setTimeout(tick,Math.round(1000+Math.random()*3000));
}
tick();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p id="test"></p>
This code I have sets the default variable to 309,000,000 but everytime I refresh the page the value doesn't save and go back to the default. Please assist on where to start with this. I've looked at local storage and cookies but don't quite understand it.

You can save the variable in sessionStorage using sessionStorage.setItem('key','value')
Docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
example: https://codepen.io/simranz/pen/GBXpPw
Another option is to use localStorage
Docs at: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Related

Html Storage resets every refresh, initialize function not working

For a website I am working on, I am trying to keep information on how many items you buy to be shown across html pages. Researching how to do this has led me to believe that Html sessionStorage is the best way to do this (if there is a better/easier way please let me know). Yet, whenever I refresh the html page or go to another page the data resets.
Here is my code:
function initialize(name, val) {
if(localStorage.getItem(name) === null) {
localStorage.setItem(name, val);
}
}
initialize("subCost", 0);
initialize("quantity", 0);
initialize("hasProduct", false);
Then since the storage only stores strings, I convert these into integers and boolean
var $quantity = parseInt(localStorage.quantity);
var $subCost = parseInt(localStorage.subCost);
var $hasProduct = localStorage.hasProduct == "true";
Before without the initialize function, I made the local storages items like this
localStorage.setItem("subCost", 0);
localStorage.setItem("quantity", 0);
localStorage.setItem("hasProduct", false);
and still converted these into those variable but they never saved with each refresh. How do I get these to save changes I make to them with each refresh.
The .setItem() method on localStorage doesn't only "sets" a "memory placeholder" for a value... It also overwrites it, if it already exist.
To save the user generated values, the best "moment" to save a "change" is the change event.
Use the same .setItem() method as in your initialize() function.
$("input").on("change",function(){
// Get id and value.
var id = $(this).attr("id");
var value = $(this).val();
// Save!
localStorage.setItem(id,value);
});
CodePen
Just as a hint...
This method to save values locally is ephemeral...
Values are kept until user closes the browser.
Not just closing the page, but closing the browser completely.
So to keep some values between pages navigated, this is the optimal use.
To store values for a longer run (like 6 months or longer), use cookies.
Have a look at jQuery Cookie plugin.

jquery library to count how many times a user has logged into my page

I am using a jquery library for cookies and want to use this cookie to count how many times a user has logged into my page.
The cookies I am using are here: https://github.com/js-cookie/js-cookie
and I am setting the cookies within a login function.
The problem is I want to pass a counter within Cookies.set( or have some sort of mechanism within this where the cookie will remember how many times the user has logged in.
Please can someone help with this?
First check if have that coockie in the page. If true, get the coockie value and add to it 1. Else, set this coocike first time in value 1:
count = parseInt(Cookies.get('counter'));
if(count){
Cookies.set('counter', count + 1);
}
else{
Cookies.set('counter', 1);
}

Keeping a user-defined JScript variable after reload?

In my HTML document, a button is displayed, and it's onclick event is to alert the variable countervar. Another button can be used to bring countervar up using countervar++. Countervar is never defined in the JScript document, because I want countervar to stay how it was last defined by a user. Like I expected, countervar was nil after each reload. Saving browser cookies also would not work, because the same variable has to be displayed to each user who views the document. I'm looking into "global variables" for an answer, but no luck. Help?
As suggested in the comments, you can use localStorage to achieve part of what you want:
var counter;
// save to local storage
window.localStorage.setItem("counter", counter);
// you can call this whenever you make changes to the counter variable
// load from local storage
// call it when the page loads
if( window.localStorage.getItem("counter") === null){
counter = 0;
}
else{
counter = parseInt(localStorage.getItem("counter"));
}
This will allow you to save the variable for one user. If you want to share it between users, it can't be done just using client side scripting. You'll have to have some sort of server storage/database.

html5 localstorage not working the way I want

I am using HTML5's localstorage to save two variables and load them when the user refreshes the page but something doesn't work properly when loading the saved item:
var's:
var cookies = 0;
var cursors = 0;
saving code:
window.setInterval(function(){
var save = [cookies, cursors];
localStorage["save"] = JSON.stringify(save);
console.log("Saved game");
}, 1000);
loading code:
function load() {
var state = JSON.parse(localStorage["save"]);
console.log("Loaded game");
}
What my console show's on page load:
[13,1]
Loaded game
[0,0]
Saved game
[0,0]
Saved game
[0,0]
Saved game
Etc.
The load() function gets called on body load (<body onload="load()">
and I DO get the console message "Loaded game"...
You syntax seems fine. However, JSLint recommends using dot notation on localStorage:
localStorage.save = JSON.stringify(save);
and
var state = JSON.parse(localStorage.save);
Then you can just add your state variable to the console.log statement to check it:
console.log("Loaded game: "+state);
Remember, your values have been saved as an array, so you'll have to access them with state[0] and state[1] to get the individual values.
There is nothing wrong with your localStorage access. Also, you don't need to try sessionStorage if is localStorage what you are looking for.
The problem, I think, is with how are you dealing with your data.
Judging by your code, you are reading the localStorage data and storing it into a local variable called state and doing nothing more with it.
Fact: if you are REALLY getting to save your data to localStorage with the
localStorage["save"] = JSON.stringify(save);
then the
var state = JSON.parse(localStorage["save"]);
would actually work, if performed anytime after the previous snippet. So, if your application is actually getting to run the snippet where you save the data, then later when you run the load function, the local variable state will have the content [0, 0].

How do you make a variable that is changing every reload?

The variable I'm talking about is like page views. I want it so the variable doesn't start at 1 every time. So every time you reload it, the pageviews variable adds by 1. All I have is:
HTML:
<div id='pageviews'></div>
Javascript:
var pageviews;
pageviews += 1;
document.getElementById('pageviews').innerHTML = pageviews;
I didn't use CSS because that was optional.
You can use sessionStorage or localStorage deppending on the behaviour expected.
$(document).ready(function() {
var currentUpdateCount = sessionStorage.getItem("updateCount") ? sessionStorage.getItem("updateCount") : 1;
sessionStorage.setItem("updateCount", currentValues + 1);
});
The sessionStorage is alive only in the time that the current session is open in the browser.
The localStorage persist after you close and open the browser again.
You can know more about the html5 storage system here
Use localStorage to store the count as :
var count = 0;
localStorage.setItem('count', count);
and use var count = localStorage.getItem('count'); to retrieve the value (remember localstorage stores as string and not as integer so you can't directly use it as an integer.
OR
Use Cookies, set a cookie by setcookie(), although you will have to set some Expiry date to it.
EDIT : This is exactly what to want to achieve. Hope it helps.
You will need to send an ajax request to the server and store it in a database.
If you only want to test your code, you can use localStorage for now and then modify the code to send the ajax request later on.

Categories

Resources