How to display updated localStorage data after page is refreshed? - javascript

2 things I would like to accomplish here:
I'm trying to display the new high score after the page is refreshed.
The high score resets to 0 after refreshing due to localStorage.setItem('high_score', 0); so I'm not sure how to properly set this without resetting it to 0 every time the page is refreshed.
let score = 0;
var high_score = 0;
localStorage.setItem('high_score', 0);
document.getElementById('high_score').innerHTML="HIGH<br>SCORE:<br>" +
localStorage['high_score'];
if (score > parseInt(localStorage.getItem('high_score'), 10)) {
localStorage.setItem('high_score', score);
}

You could only set the storage item except when you need to update it:
// assuming the scores will not be negative
const newHighScore = Math.max(localStorage.high_score, score);
localStorage.high_score = newHighScore;
And then when using the storage value, alternate with 0:
document.getElementById('high_score').innerHTML="HIGH<br>SCORE:<br>" +
(localStorage.high_score || 0)

Related

How can I adjust in my Jquery Code see description of problem

Currently right now it adds up a visit counter. Example: I have a text field and I type 1 then next text field I type of 20 so 1 of 20 visits. Next document I use it uses the same counter so it would automatically calculate up the visits for me to say 2 of 20 visits. What I want to figure out is if I need to change the counter to say 3 of 20 instead of 2 out of 20 how can I adjust the code to save my changes.
Currently the counter reverts back after I save my document with the counter in it- reverts back to 2 of 20 not reflecting me changing it to 3 of 20.
window.onload = function(e){
setCurrentCount('previousvisit','currentvisit','totalvisits');
}
function setCurrentCount(prevId, currentId, totalId ) {
var prevEle = document.getElementById(prevId);
var currentEle = document.getElementById(currentId);
var totalEle = document.getElementById(totalId );
if( prevEle && currentEle && totalEle ) {
var totalVal = parseInt(totalEle.value);
if( totalVal > 0) {
var prevVal = 0;
// check the prev value
// if it is empty, set it to the total value
if(! prevEle.value ) {
//currentEle.value = totalVal;
prevEle.value = totalVal;
} else {
currentEle.value = parseInt(prevEle.value) + 1;
}
}
}
}
If I change the counter to reflect a different number outside the initial calculation I want it to save it- right now it reverts back to the number it actually should be in the calculation.

Adding data objects integers to localstorage

I want to add data objects returned from the server and store them in local storage.
data.Total is a set of integer numbers that come from the server on successful requests.
I somehow need to add them before storing them in local storage
let score = data.Total+localStorage.getItem("RelationScore");
let removeNull = score.replace('null', '');
localStorage.setItem("RelationScore", removeNull );
Example Output: 1234
I want to add those and store them to a single variable, so the result based on the example should be 10
All items are saved into localStorage as string, So you will need to parse them first:
let score = localStorage.getItem("RelationScore");
score = score === null ? 0 : parseInt(score);
localStorage.setItem("RelationScore", data.Total + score);
I assume that data.Total is an integer like you said. If it is not, then you'll have to parse it too.
If you want to only update the total when the item is not zero:
let score = localStorage.getItem("RelationScore");
if(score !== null) {
score = parseInt(score);
if(score !==0)
localStorage.setItem("RelationScore", data.Total + score);
}
Based on your comments, you're probably looking for this code :
let stored = (localStorage.getItem("RelationScore") === null ? 0 : parseInt(localStorage.getItem("RelationScore")));
let score = parseInt(data.Total) + stored;
localStorage.setItem("RelationScore", score);
Even if you put an Integer into localStorage, it's going to be saved as a String.
If you add a number to a String in JavaScript, you are just appending the number to the String, "10" + 1234 === "101234";. So you will need to parse the String to a number:
let score = 0;
if (localStorage.getItem("RelationScore")) { // if the Item exists
score += parseInt(localStorage.getItem("RelationScore")); // make a number out of it and add it to the score
}
score += parseInt(data.Total); // add data.Total, even if the Item hasn't already been set
localStorage.setItem("RelationScore", score); // finally save the score to localStorage

How to give javascript sessionStorage new name with loop

I am trying to make a button, which creates some data and saves it in the sessionStorage. I want to give every data a key number from 0 and up. The first time the button is pressed it gets the name/key 0. If the button is then pressed again the name for the new data string/object would be 1 and so on. The thing is that I dont want to overwrite existing data in sessionStorage, so it should check if there is a string/object in the sessionStorage; if yes give it a new name, if no save it.
In my following code, cpData is the data I want to store in sessionStorage:
for (var index = 0; index <= window.sessionStorage.key(index); index++) {
if (index > window.sessionStorage.key(index)) {
window.sessionStorage.setItem(index, cpData);
break;
}
};
I found out by myself. This code should do it if one is needs the to do the same:
for (var index = 0; index >= window.sessionStorage.key(index); index++) {
if (window.sessionStorage.key(index) === null) {
window.sessionStorage.setItem(index, JSON.stringify(cpData));
break;
} else if (index > window.sessionStorage.key(index)) {
window.sessionStorage.setItem(index, JSON.stringify(cpData));
break;
}
};
This time it checks wether or not window.sessionStorage.key(index) isn't there. If so it will create a datastring. The break; statement stops the loop immediately. Now the next time the button is pressed and the loop is started, it can see that there is already a datastring, it will then continue to loop until index value is bigger than the key biggest key value at the moment. When it is bigger than al previous saved data, it will save the data and break; the loop.
If one wants to check it by him/herself add this to the same script:
var i = 0, oJson = {}, sKey;
for (i; sKey = window.sessionStorage.key(i); i++) {
oJson[sKey] = window.sessionStorage.getItem(sKey);
}
console.log(oJson);
This will print out ALL sessionStorage data in console.

Javascript timer used in points system

I am trying to make a game. There are blocks falling and a main block which the user commands that is trying to avoid them. There is a point system that is supposed to add 10points each time the red cube touches one of the extremities. The problem is that it adds 10 points per each 10 milliseconds that the cube stays in the extremity. How can I solve this??
You just need a flag that you set and then clear whenever you touch the side.
Since the box starts touching the side, i initialized already_touched to true.
var already_touched = true;
Then your logic below becomes:
if (mySprite.x == 450 || mySprite.x == 0) {
if (!already_touched) {
already_touched = true;
count += 10;
}
var alert1 = document.getElementById("score");
alert1.innerHTML = "Score: " + count;
} else {
already_touched = false;
}
Working demo here: http://jsfiddle.net/KrZq9/

Implementing voting logic based on previous score

Wondering how to handle this. I've done it previously, but it involves a lot of if/else statements and I can't seem to figure it out without resorting to that. I posted it on codereview and got someone to help me re-facor it, but now I'm trying to get this functionality working properly.
How this works now is, if you click "up", it'll increase the score 1 point. If you click "up" again, it'll decrease the score. That's fine. If you click "down" it'll have the same behavior. It will not however go below 0 ever, since I don't want to display a negative score.
Right now I'm just checking to see if the previous or next buttons have .upColor and .downColor css classes on them, which check if they've already voted. I'm having trouble trying to update the proper score based off of this especially if the original score is 0, or if the score is 10.
Logic I'm trying to implement:
E.g. Original score is 0:
User votes up. Score goes to 1. User votes down. Score goes to 0 (not -1)
User votes down. Score stays at 0. User votes up. Score goes to 1.
E.g. Original score is 10:
User votes up. Score goes to 11. User votes down. Score goes to 9.
User votes down. Score goes to 9. User votes up. Score goes to 11.
Code:
$(function() {
var handleClick = function($btn) {
var $voteContainer = $btn.parent();
var scoreNode = $('.count');
var originalScore = Number($voteContainer.data('original-score'));
if ($btn.hasClass('down')) {
if ($btn.prevAll('.up').hasClass('upColor')) {
$btn.prevAll('.up').toggleClass('upColor');
alert('voted up now voting down, decrease 2 points, but don\'t go below 0.');
}
}
if ($btn.hasClass('up')) {
if ($btn.nextAll('.down').hasClass('downColor')) {
$btn.nextAll('.down').toggleClass('downColor');
alert('voted down now voting up, increase by 2 points');
}
}
var increment = $btn.hasClass('up') ? 1 : $btn.hasClass('down') && originalScore > 0 ? -1 : 0; // default
// Only do something if there is an increment
if (increment) {
var currentScore = Number(scoreNode.text()) || 0;
var newScore = currentScore + increment;
var diff = Math.abs(originalScore - newScore);
// Can't go more than + or - 1
if (diff > 1) {
newScore = originalScore;
}
// Set new displayed value
scoreNode.text(newScore);
}
$btn.hasClass('up') ? $btn.toggleClass('upColor') : $btn.toggleClass('downColor');
};
var upBtn = $('.up');
var downBtn = $('.down');
upBtn.add(downBtn).click(function() {
var $btn = $(this);
handleClick($btn);
});
});
Demo: http://jsfiddle.net/3kCPw/
I won't rewrite your code because it will take me too long, but I will give you some code that I would have used from the start.
Start with the original number:
var original_vote = 2;
var current_vote = original_vote;
Keep this as a constant to refer to for the future. Then when you click the up vote, you can add 1 to that simply with:
current_vote = original_vote + 1;
Then un-checking the up vote would make it:
current_vote = original_vote;
Then just do the opposite for down voting.
Keeping the original number ensures that you will not accidentally make the votes go out of the scope that it should.
Hope this helps!

Categories

Resources