Local Storage not stored after page refresh - javascript

I'm having a really hard time understanding what I did wrong in my code in order to have a value saved in local storage.
I have a pretty big code project so I'll try to summarize what the program is tryin to do overall.
I am pulling news articles from the news API and displaying the articles; each article (depending on the publication it came from) pushes a different numeric value into an array allSource2.
I then take the sum of this array to arrive to a "score" (variable is called sum)
I basically want that score to be locally stored, so that it is available even after a page refresh.
I think something wrong might be happening because of where I put the localStorage function. Currently I put it under the click event that also pushes the numeric value in the array (when you click the article title).
I am super confused at where else it could be, so that it truly updates the sum every time that sum changes.
Also, it does work to store it (I checked localStorage on the console, after a refresh it still works, but after refreshing and then clicking on another article, it resets to whatever the value of this article is)
I didn't put the entire code, as it's insanely long. everything else is working fine, it's just that.
Also, the all of this is contained within one big function
I define let sum =0; at the beginning of the code.
Then, this is the click event.
document.getElementsByClassName('article-rating')[i]
.addEventListener('click', function(event) {
sum = allSource2.reduce((tempSum, val) => tempSum + val);
console.log("article score is now" + " " + sum);
var lastname = localStorage.getItem("overallsum");
localStorage.setItem("overallsum", sum);
});
I also tried to put the var lastname = localStorage.getItem("overallsum"); at the beginning of the code, when the first function but no luck.
Thanks a lot for your help!
and apologies for any formatting issues, I'm super new to this.

Each time you click the event the overallsum is getting set and that is the problem. If the overallsum is a one time store to the local storage then you can check if the value of overallsum is null, and if so store the value for the first time.
Example:
if (localStorage.getItem("overallsum") === null) {
localStorage.setItem("overallsum", sum);
}
Otherwise, if the overallsum is something, then for every individual article you could 2D array and then set the value with the same conditional check.

Related

How can I add permanent data into an variable

I'm working on a project that plays a game of rock paper scissors
the game works fine but i want to add something into it. a pointing system where it will add 1 each time a player win but i can't seem to make this work i've been trying to find workarounds for almost 2 day now but i can't seem to find any solution. The thing is the code works but after i log the function that adds 1 to a variable but after that it returns to it's original value which is 0.
const one = 1
function addone(test){
test += 1
}
addone(one)
console.log(one)
This print the original value like the function did not do anything to it. im so confused.
I see two problems in your code:
one is a const variable. That means that you can't modify its initial value.
test is a local variable inside your function, that means function won't modify the values of the variable that you pass as parameter (one).
There is an operator(++) that add a unit, I highly recommend you to use it instead of make a function:
var one = 1
one++;
console.log(one)
If you want to use a function you have to do like this:
var one = 1
function addone(test){
return test+1;
}
one = addone(one);
console.log(one)
In terms to store permanent data into a javascript variable, that's not possible. Variable are stored in RAM, that means that when you stop the program, al data of your program are wiped. Permanent store are made in database and other complex data structures.
If you want to play multiple games, you should consider to allow the players to play more games before the program finish.
thank you very much i never think that i could get more dumb so i cant manipulate it because it's just a copy of that variable that im inputing as parameter? so it means that the function did not touch the variable at all. I wish i could go back to my mother's womb.
and the const it's just a typo very sorry for this.
i did not know this website is very active i thought i would wait days just to get a response thank you very much and have a nice day

Qualtrics: Save previous slider response and set as default in next slider

I was wondering if someone can help me out on the following issue:
Participants are presented different behaviours that they have to rate on a slider from -3,-2,-1,0,1,2,3. All behaviours are presented on separated pages. Now, I want each previous response to be the default function of the behaviour that is presented next.
For example:
Participant is shown first behaviour, default setting is "0". He/She rates the behaviour with "-2".
Participant is shown second behaviour, default setting is now "-2".
Etc.
I understand that I have to set an embedded data variable.
I was told to save the participants slider response and keep overwriting this. However, I'm very new to Javascript and I'm not sure how to save the participants' slider response.... Any help would be hugely appreciated!
I think for overwriting the embedded data variable 'Output', I use:
[Qualtrics.SurveyEngine.setEmbeddedData('Output', 'response_variable');
However, I am not sure how response_variable can capture the sliderresponse.
This 'response_variable' is just a placeholder from some instruction you received, you need to declare variable to store value of your slider and pass this variable as second parameter.
To save value (Docs:
getChoiceValue,
addOnPageSubmit,
setEmbeddedData):
Qualtrics.SurveyEngine.addOnPageSubmit(function(type)
{
if(type == "next")
{
var value = this.getChoiceValue(1); // assuming sliderId == 1
Qualtrics.SurveyEngine.setEmbeddedData("Output", value);
}
});
To set value in next question (Docs:
setChoiceValue
):
var lastValue = "${e://Field/Output}";
this.setChoiceValue ( 1, lastValue );
PS. You may also need to store information about direction (next/previous) and add condition to avoid setting value after click on "previous" button
PS2. In case this did't work see also this thread

how to refresh php div every few seconds

So I'm basically trying to implement an online trading card game in php and (maybe minimal) javascript, and so far I have a GUI set up in php, a database with the required tables (so far) to hold the decks, fields, and other various data. I've got it to the point where i have a function that initializes the fields for both players and populates their fields and hands with cards from their deck. I also got it to the point where a player on another computer or device can take the room number of the game and join the game so the see the exact initialized field.
my next objective was to be able to set up the turn logic, and allow the screen to update for one player while the other is making plays during their turn. My problem is I'm not sure what the minimum viable solution will be for this, because I have long intricate functions that display the current field based off of values that come from a field table. So my ideal logic is set up like this:
//find game form
//host game form
//if host is set (post){
//call insert field function (a long function that creates a table for the current game being played and initializes the field and hand with random cards from the deck table)
//link game to host for future field printing
// populate host function (a function that prints a table of every card on the field with the most up to date variables to represent each spot)
}
//if find is set (post){
//call insert field function
//link game to host for future field printing
//a button form to start the game which begins by calling heads or tails
// populate find function (same as host but for find player side)
}
//if start game is set (post){
// do game logic such as coin flip which will be notified to opponent in a message field in the game table upon the refresh
}
I was wrapping the populate host function in a refreshable div like this:
print "<div><meta http-equiv='refresh' content='5' />"; //host populate just disapears
populatehost($roomnumber); //populates self and opponents in hosts perspsective
print "</div>";
so that the function would be called every 5 seconds or so, but this just causes the field to disappear after 5 seconds. So...
Why is it disappearing?
How can i get it to refresh the page and just display one instance of the field using the populate field function?
Is this approach viable? if not, what's the easiest approach I could take and how?
I also tried a solution where the function was called every 5 seconds and gotten rid of, but i'm not sure if I was doing it right, the PHP manual didn't explain it very clearly, and after lots of trial and error i think i crashed my server. It was something like this:
//loop
ob_start();
populatehost($_SESSION['gamenumber']);
sleep(5);
ob_end_clean();
I kept playing around with that logic but it either printed infinitely, didn't print at all, or crashed my server. I'm afraid to play around even more for fear of crashing the server again. Maybe someone can explain the correct way to do it or why it is not viable if it isn't?
I'm sorry if these are dumb questions, I've spent days and days researching approaches to this problem, I wasn't sure if I could implement it using javascript or ajax along with my field printing function, I tried some and they weren't working, and I'm not sure if it's because my approach is viable or not.
You can take javascript or Ajax help for div you can assign id to the div and call id in javascript:
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 2500)
})
check this fiddle:
http://jsfiddle.net/arunpjohny/asTBL/
Thanks

How to get unique id from localStorage for delete button

I have been trying for getting an id from localStorage but unable to achieve it.
My localStorage inside events contains such as below.
[{"id":"ef5","title":"wan","start":"2016-05-12","end":"2016-05-13"},{"id":"ef6","title":"wana","start":"2016-05-21","end":"2016-05-22"},{"id":"ef7","title":"haha","start":"2016-05-25","end":"2016-05-26"},{"id":"ef8","title":"asdas","start":"2016-05-20","end":"2016-05-21"},{"id":"ef9","title":"sdas","start":"2016-05-19","end":"2016-05-20"}]
Now i will provide 2 coding with different method that i have tried so far. For information, i look through into this topic: localstorage: Get specific localstorage value of which contains many items
but none works for me.
I did tried coding as below:
1st method:
$("#deleteEventYes").click(function(){
var indexDel = localStorage.getItem("events");
var deleteId = calEvent.id;
var result = localStorage.getItem("events");
function getItemHrefById(json, itemId){
return $(json).filter(function(){return this.id == itemId;})[0].href;
}
var href = getItemHrefById(result, deleteId);
alert(href); });
Above code show some kind of array method (i think) where i'm using indexDel to get item from localStorage (events) while deleteId i took from calEvent.id which is the id for the event that has been clicked for to be deleted. Other than that, i think you guys know what it is. However for this method, i use result variable instead of indexDel. Thus don't mind if i getItem from localStorage 2 times
2nd method:
for (var i = 0 ; i < indexDel.length ; i += 1) {
if(deleteId == indexDel[i].id) {
return indexDel[i];
console.log(deleteId);
console.log(indexDel[i]);
}
}
return null;
Above code is using custom loop i think. The declaration of variable for indexDel is still the same with first method. I try to use the refactoring method but it seems its hard for me to understand how is it to be done. Is it because my variable placement is wrong? or is it because it is not suitable for my case?
NOTE: I want to delete an event inside eventClick function, and so far i did retrieve the id and remove the event from the calendar based on id. However my only problem now is to match the deleted event id with the id inside my localStorage and remove the item. So far getting an id from the is quite complicated for me.
UPDATED
I already done something like this but still don't work. Anyone can tell me what went wrong here? It is not giving me any error but it just do nothing. Not even delete.
https://jsfiddle.net/v35a2o07/3/
Never mind. I think i figure it out :)
It is because i forgot to setItem & stringify it after using splice.
Here i can assume splice is the same as add/remove such wrote at w3school
http://www.w3schools.com/jsref/jsref_splice.asp
"The splice() method adds/removes items to/from an array, and returns the removed item(s)."
My final code is on this fiddle given: https://jsfiddle.net/v35a2o07/4/
So the concept is:
1) First step is declare one variable that parse your localStorage key such asvar items = JSON.parse(localStorage["events"]); so that you can use it for the loop
2) Use for loop to determine the length of localStorage based on localStorage key that we parse on No. 1
3) Use if statement to check the comparison between localStorage data with our desire data such as if(items[i].id == deleteId){
4) This is OPTIONAL but important. To enable you to check the comparison is right, create one alert or console.log() and stringify it because if you don't, you will only see [object,object]. The coding such as alert(JSON.stringify(items[i])+"<<<>>>"+deleteId); Make some else statement too if you want to be sure.
5) When all the conditions are correct, then you are ready to do some action to it. For my case, i just use splice() to delete it. It is also can be used to add item. I am not sure how is it done but try to search for it to get more info.
6) After splicing it, it is safely to break and get out from the loop.
7) This is important otherwise, it will not work. Don't forget to set it back to localStorage and stringify it such as localStorage.setItem('events', JSON.stringify(items));
That's it.
I wish this would help anyone that needs it. If i have make wrong statement or wrong concept, please make correction and clarify it for anyone.
Cheers.

how to implement javascript localStorage

I want to implement localStorage for one of my values in my Achievements class. So basically what this class does is take player data from backend database and if a player clears certain tasks an achievement gets unlocked. For now I have just 1 achievement defined as follows
Achievements:{ 1:{name:'First_Achievement',status:1} },
The status field acts like a flag for my achievements. If status is 1 then achievement is still locked and if it goes 0 the achievement gets unlocked.
This is a skeleton code for when my achievement gets unlocked. This block of code is checked in my game every 10 seconds to see if a certain task is cleared to unlock an achievement
checkAchievements:function(){
this.probsSolved = this.getTeamProbSolved();
if( this.Achievements[1].status == 1 && this.probsSolved.length >=3)
this.triggerAchievement(1); // spawns achievement 1 on screen
this.Achievements[1].status = 0;
},
So this works fine when I run the game. The "this.Achievements[1].status" is set to 0 until I start my game again the next time. It sets the "this.Achievements[1].status" back to 1 and the if loop runs again as status is set back to 1 which I don't want because its obvious I want my achievement to be spawned or displayed just once and not every time I run the game.
So how do go about an implement localStorage here? I suppose I need to store my "Achievements.status" field in the localStorage so that the if loop runs just once and not everytime. Or is there any other way I can implement this?
I tried the following
localStorage.setItem(this.Achievements[1].status,0);
but it does not work
any help would be appreciated! Thanks!
First, I'd recommend reading the documentation on localStorage at MDN - https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage. Next, let's look at your call:
localStorage.setItem(this.Achievements[1].status,0);
This says: I want you to store a value, 0, and retrieve it by the key that is the value of this.achievements[1].status.
That seems to be booleans for you. So you basically did:
localStorage.setItem(true, 0)
The localStorage API expects a string for the keyname, so it will get the string value of true which is, true. So it probably did work for you, but you used a key that probably isn't what you want. You need to think of a key name scheme that makes sense for you.

Categories

Resources