Keeping a user-defined JScript variable after reload? - javascript

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.

Related

how to save state of the page when refreshing? (HTML, JS)

(DISCLAIMER: I'm new to coding so my code probably isn't optimal. If you know a better way to do it, feel free to leave it in the comments )
Most of the time I had no idea what I was doing, but with patience and with you guys' help I came up with this:
if (window.localStorage) {
// Create the Key/Value
var cNum = localStorage.getItem("currentNumber");
if (localStorage.currentNumber == undefined) {
localStorage.setItem("currentNumber","0");}
// Variables
resetCount.innerHTML = localStorage.currentNumber;
// Functions
function btnR() {
cNum++;
localStorage.currentNumber = cNum;
resetCount.innerHTML = cNum;}}
else { console.log("No"); }
HTML:
<button id="resetButton" onclick="btnR()">Reset</button>
<p id="resetCount">0</p>
I was creating a button that each time you click on it, it reset the checkboxes, but I also wanted a counter to see how many times they got rested. The problem was that every time I click the button the counter also reset. Now that is solved I can try to apply the same thing for the checkboxes, so they don't reset on refresh either.
Note: I had to put the .SetItem in an if statement cause, even tho the value was in storage it kept setting back the value to zero every time I refreshed the page. This was the way I found to stop that.
You either need to set up a back end to send data to and save the information you want to keep stored, or save data in localStorage.
Just know it is not the best practice to save sensitive info in localStorage (as they can be compromised in cross-site scripting attacks).
localStorage.setItem puts a bit of data into localStorage (and that stays there till you clear it) and localStorage.getData extracts it.
This might help get you started on localStorage, but you will have to figure out the function to set the colour to the element you have.
let boxColour = localStorage.getItem("boxColour");
if (boxColour === null) {
setBoxColour("colour");
} else {
setBoxColour(boxColour);
}
function setBoxColour(colour){ localStorage.setItem("colour");}
/* Inside the function you have to get the item and change it's style attribute or add a class to add styles */
Careful with that localStorage data!
You could use LocalStorage.
It saves data in the page to be used after when the page is refreshed or closed and opened later.
Theres a example:
(Unfortunally, it seems to not work in the stackoverflow site, but if you try at your HTML file it will work)
var loadFunc = (elem) => {
console.log("Value saved is: "+ localStorage.getItem("savedValue"));
if(localStorage.getItem("savedValue")){ //checks if value is saved or not
elem.checked = localStorage.getItem("savedValue");
}
}
var clickFunc = (elem) => {
localStorage.setItem("savedValue", elem.checked); //set te value if in localStorage
}
Click the checkbox and the value will be saved.
<input type="checkbox" onload="loadFunc(this)" onclick="clickFunc(this)">

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.

Attempting to use a global array inside of a JS file shared between 2 HTML files and failing

So I have one HTML page which consists of a bunch of form elements for the user to fill out. I push all the selections that the user makes into one global variable, allTheData[] inside my only Javascript file.
Then I have a 2nd HTML page which loads in after a user clicks a button. This HTML page is supposed to take some of the data inside the allTheData array and display it. I am calling the function to display allTheData by using:
window.onload = function () {
if (window.location.href.indexOf('Two') > -1) {
carousel();
}
}
function carousel() {
console.log("oh");
alert(allTheData.toString());
}
However, I am finding that nothing gets displayed in my 2nd HTML page and the allTheData array appears to be empty despite it getting it filled out previously in the 1st HTML page. I am pretty confident that I am correctly pushing data into the allTheData array because when I use alert(allTheData.toString()) while i'm still inside my 1st HTML page, all the data gets displayed.
I think there's something happening during my transition from the 1st to 2nd HTML page that causes the allTheData array to empty or something but I am not sure what it is. Please help a newbie out!
Web Storage: This sounds like a job for the window.sessionStorage object, which along with its cousin window.localStorage allows data-as-strings to be saved in the users browser for use across pages on the same domain.
However, keep in mind that they are both Cookie-like features and therefore their effectiveness depends on the user's Cookie preference for each domain.
A simple condition will determine if the web storage option is available, like so...
if (window.sessionStorage) {
// continue with app ...
} else {
// inform user about web storage
// and ask them to accept Cookies
// before reloading the page (or whatever)
}
Saving to and retrieving from web storage requires conversion to-and-from String data types, usually via JSON methods like so...
// save to...
var array = ['item0', 'item1', 2, 3, 'IV'];
sessionStorage.myApp = JSON.stringify(array);
// retrieve from...
var array = JSON.parse(sessionStorage.myApp);
There are more specific methods available than these. Further details and compatibility tables etc in Using the Web Storage API # MDN.
Hope that helps. :)

Unable to set selected attribute after page loads

My html page with SELECT and OPTIONS values sets one of the options as a default.
Were the user to choose a different option, which then takes him to a new page, I’d like to preserve that value so the next time home page is generated the value the user selected should remain on display, rather than the original default value, when the window reloads.
How do I do this in javascript?
I had tried to save values via a DOM capture of the selected value, but I don’t seem to be able to change that original default value.
E.g.,, one line of code reads:
window.location.reload();
yet were I to use “hold values” to capture the user’s selected option that differs from the default option, like so:
var holdPick = document.getElementById(“uPick”).value;
window.location.reload();
document.getElementById(“uPick”).value = holdPick;
that won’t do the trick, and I know not why.
When you reload a page, all the JavaScript is reloaded too. So, that's why the JavaScript snippet you posted doesn't seem to be working... The line after window.location.reload(); isn't even run at all. If you want to have a value that persists between page loads, you'll need to set and retrieve a cookie. Check out the JavaScript document.cookie API at MDN. That should tell you what you need to know about storing and retrieving your value in a cookie.
Why: every time var holdPick is executed it will create variable from scratch.
Second line tells the browser to reload page, so the third line never gets the chance to be executed.
I'd recommend usage of HTML5 Web Storage
if (sessionStorage.uPick) { //check if variable has been set already
document.getElementById(“uPick”).value = sessionStorage.uPick;
} else {
sessionStorage.clickcount = document.getElementById(“uPick”).value;
}
you can use cookies also, but I don't think it is as straight forward.

How can I bind own data to the history object using JQuery Mobile?

I'm looking for a nice way to bind my own app data (like currentQuestion, currentAnswer) to the history object.
I tried to keep track in the hashchange event, but that gets complicated.
I try it with url parameters, but I want to have status object with some entries for each element on the history stack, so I would have to have many parameters.
Is there a way just to add an object to the history stack?
If you use jquery mobile ajax transition you will have access to the same global jquery object on all pages, you can append data to it, for example in the first page you assign currentQuestion and currentAnswer
$.currentQuestion = 'something';
$.currentAnswer = 'something';
On the next page you can access these variables easily
console.log($.currentQuestion);
That is how I move data between pages inside jquery mobile
I found the way. You can just insert variables into the history stack:
var urlh = $.mobile.urlHistory;
if( "factId" in urlh.stack[urlh.activeIndex] ) {
// load
cp10.score.currentFactId = urlh.stack[urlh.activeIndex].factId;
} else {
// store fact id in history object
urlh.stack[urlh.activeIndex].factId = cp10.score.currentFactId;
}
Here I insert a variable 'factId'. If it is not already in the stack element (what happens when the page is first loaded), then insert it. Later (when hte user hits the back button or so) you can retrieve it from there.

Categories

Resources