So I have a JavaScript variable called addNumber which just adds a number by 1 to a div any time I click a button. But I'm using it on a website which has multiple pages, and every time I change pages, it resets the counter. I've used console.log() to check the variable multiple times, and it always resets back to zero any time I leave the page, even when I keep the tab open. This counter is kept at the top of the page for all to see, and I want it kept there in a navbar, kind of like the shopping cart on Amazon. Is there a way I can do something like that using only vanilla JavaScript?
Thank you.
You may find this link helpfull.
https://www.w3schools.com/jsref/prop_win_localstorage.asp
Quick answer you store key value pairs using a string tag to identify them:
localStorage.setItem("lastname", "Smith");
localStorage.getItem("lastname"); //this returns the string "Smith"
Edit: i do not recommend you doing this in a production enviroment. You should stick to the framework of the project. If the project has no framework or is just for school or learning purposes then i guess is a viable option.
You can store a variable in localStorage to access it somewhere else through
Try using:
function onClickevent(){
addNumber = addNumber +1
localStorage.setItem('counter', addNumber);
}
Then get it through
//Just assign it to your div
const getIt = localStorage.getItem('counter')
Here is some documentation on LocalStorage and how to use it :)
https://www.w3schools.com/jsref/met_storage_getitem.asp
https://blog.logrocket.com/localstorage-javascript-complete-guide/#:~:text=To%20get%20items%20from%20localStorage%2C%20use%20the%20getItem()%20method,in%20the%20browser's%20localStorage%20object.
The solution you can try is :
In the .js file at the end of all lines, type
window.localstorage.setItem("addNumber",addNumber);
The addNumber will be stored with an ID of addNumber.
To later retrieve, use :
window.localstorage.getItem("addNumber");
You may assign the above to a variable like
var number =....
Then console the number.
I hope this helps.
Related
hello I have a small project I'm working on.
the project is calling an API with ajax and getting info about currencies, one of the things I'm stuck on is that I have to write them in cards that include a checkbox that has to stay activated after I refresh the page.
any suggestions?.. please I'm desperate
When you make your call on your API just set the checked value on the correct checkbox, please have in mind that setting checked=false will still give you a checked checkbox.
<input type="checkbox" checked>
One way to preserve information against a page refresh is to use localStorage.
LocalStorage allows you to store key:value variable pairs in the local browser. You can view the localStorage values for any given website in DevTools F12, on the Application tab. The variables are stored by website, and remain as they are until (a) they are deleted, or (b) browser cache is cleared. (For more info on when localStorage is cleared, see this answer).
LocalStorage is dead-simple to use:
let myPet = 'Cat';
localStorage.setItem('animal', myPet);
And to read it:
let myPet = localStorage.getItem('animal');
What you might want to do in your project, perhaps on a timer - or after the ajax call - is loop through your fields and create an object with all the fieldnames/values. Then use JSON.stringify to turn the object into text that you can store in a localStorage variable.
Note that you will need to write something that on page load ( $(document).ready() ) will see if the fields are empty and if there is a RECENT localStorage variable (so, you might want to create second localStorage variable (you can have MANY) that has the last-updated datetime) then you read the JSON string into a javascript object and populate your field values.
I would recommend using a dictionary, putting something unique like an ID of those currencies that are checked at that time.
If the new answer you get has the same currencies as before plus more, you can use that dictionary in memory to check those items again. If you don't get the previous response, you can just add those new items to avoid unchecking the checked currencies.
Exmaple:
var dictionary = {};
// here you should do a forEach in currently checked currencies
...
dictionary[id] = value; // (true, because it is the value of checked)
Hope it helps you.
I am now writing a cookie for the browser in google tag manager, so as to calculate the page score. But I have a problem that the gtm.timer ran a couple of times, and the score just being added for multiple times, when the timer keep triggering.
And now I come up with a idea, that I can use the datalayer variable as a condition (i.e if the timerEventNumber is greater then 1 then do not return new value).
However, the problem is, how can I reference the value of the data layer variable from a custom javascript?
Many thanks for your help in advance!
You should be able to simply define your Data Layer type variable as gtm.timerEventNumber and use that in your Custom JS variable, eg. if you've named your variable as "DL - gtm.timerEventNumber":
function(){
if ({{DL - gtm.timerEventNumber}} > 1){
// do stuff
}
}
This seems like a fairly simple question... I am trying to overwrite the data from cookie a with the data that is stored in cookie b but without changing either of the names of the cookies. Cookie b contains the particular user's defaults while cookie a stores the users current selections.
I have looked online and taken a few shots in the dark but, I have no leads! Everything that I've tried overwrites the entire cookie and I only want the data in cookie a to be changed, with no changes to the names of the cookies or to the data of any other cookies
Is this possible? If so how can I accomplish this task?
Thank you in advance!
Here's the code. It's commented enough to answer the question:
//first, get the "b" cookie's value
var cooks=document.cookie;
//just the "b" part of the cookie string
var bStartIndex=cooks.indexOf('b=')+2; //get the start of the b part of the string
var bEndIndex=cooks.indexOf(';',bStartIndex); //and the end of it
//and then extract the actual variable value from it
var b=cooks.slice(bStartIndex,bEndIndex!==-1?bEndIndex:null); //in case b was the last var, there would be no ; after it, so bEndIndex would be -1
//now, we set a to that
document.cookie='a='+b; //I don't THINK this will overwrite other cookies
I haven't tested it, but it SHOULD work. Tell me if it doesn't and I'll try to fix it
There are probably libraries out there that could make this a lot easier, if you're planning to use this in production
Please don’t answer this if you don’t take the time to understand my question or have a reasonable answer. I have got a few answers that is far on the side and I think I explain my problem very clear. Shall this problem drive me nuts or is there somebody out there with a straight and clear answer on Titanium.App.Properties?
I have a login form that stores the username in one:
Titanium.App.Properties.setString("userName",e.value);
and the password in another:
Titanium.App.Properties.setString("passWord",e.value);
The forms TextFields holds these values(after a store) even if I close the window, shut down and restarts the app. This because of the App.Properties.getString("value"); I suppose….?!
But when I copy the hole form with its App.Properties.getString("value"); to another window, the TextFields are empty and contains no value at all. I understand that the Properties string must be there some where in App.Properties, but how can grab it and use it another place in the app?
My question is: How to get the value from my
var userNameValue = Titanium.App.Properties.getString("userNameValue");
to be available in another window or for the hole app(global)? How can I grab it and make use of it a another place in the app? I don’t see a good reason to make these, only separate words, into objects(JSON) since the userName only contains a e-mail address and the passWord consist only of continuing letters or numbers. But if you mean I have too, -how do I set this from my TextField and get it in another TextField somewhere else in my app. I have not had any luck so far. I hope you can help me out and I can keep sane.
Titanium.App.Properties.getString("userNameValue");
This is globally Available, any Propertie of the Titanium Object is accessible in each file.
but if for some reason this doesnt work for you and you want to set a global variable,
you could do the following:
Create a file called myGlobals.js //or anything else,
//Put this in there e.g
var myProperties = {};
in any file you want to use it write in the first line
Ti.include('myGlobals.js');
Then you can make a propertie global available, for example write this in app.js somewhere where the app initializes
myProperties.Username = Titanium.App.Properties.getString("userName");
Then you can get the value in each file by accesing the propertie
myProperties.Username
//of course the Propertie has to be set before you can get them
( Titanium.App.Properties.setString("userName",e.value); ) //like you do it
But, Titanium.App.Properties.getString("userName");
should be avilable from any file anyway, (but you can give this a try although i dont think its nice to do it like this)
i had a similar problem where this didnt get any value from a propertie set in the ios settings as default value.
I had to go to the settings and manually change or edit the default value and then after a restart
Titanium.App.Properties.getString("userName");
returned the value as it should,
i hope this helps you =)
Answer to the Comment
I'm glad i could help you =)
Yes you can Use an focus EventHandler like this :
textfield.addEventListener("focus",function(){
textfield.value = "Test";
});
Beside that , are you using the identical Textfield for both windows ? like
var Textfield = Ti.Ui.createTextField({...});
and add it to 2 different windows ?
win1.add(Textfield);
win2.add(Textfield);
That led for me to Problems with labels in TableViewRows, using an identical Row 2 times in the TableView
The Text displayed only on 1 Label, sometimes it switched the Labels
I think you can't add one and the same titanium object to more then one other object
Maybe that could be the culprit,
dunno just an idea =)
I have a html page that sets a value onclick using a js function. I need to use this value in another html page. I am unable to do it. It seems to reset the value when I use the value from the second page. The .js file has been included in both the html pages. How do I retain the set value across multiple html pages?
Within JavaScript itself, you cannot keep track of variables across page loads. To pass the variable from one page to another, you will need to use a 'man in the middle' to help out. Either a cookie, or a query string.
A cookie would work great! I won't go into specifics of setting/getting cookies in JavaScript as there is excellent documentation here:
http://www.w3schools.com/JS/js_cookies.asp
Using those set and get methods (which of course you could customise to suit your needs):
First page:
var yourVariableToSave = 'I like cheese and crackers';
var numDays = 10; //How long the cookie should last.
setCookie('SomeCookieName', yourVariableToSave, numDays);
Second page:
var yourVariable = getCookie('SomeCookieName');
alert(yourVariable); //Displays 'I like cheese and crackers'
If you only want the cookie to last the duration of the current settings, you can modfy the setCookie function to not specify an expiry date.
If this is for a single request, a query string might be useful. To do this, you could append ?someQueryStringName=YourVariableValue to all links on the page, or inject the query string when the user is about to load another page. I won't go in depth with this option as I suspect a cookie may be a bit better.