text.splice(); array item deleted and saved when reloading sketch - javascript

I need some help.
I'm trying make it so that when I use text.splice() it keeps the changes when i reload the page.
Here is what I'm trying to do. It will Delete the item of the array that I wrote in the input element, but its not saving the changes made with splice().
function DeleteButton(){
const dltinpt = Deleteinput.value();
const index = secretPasswords.indexOf(dlinpt);
if (index > -1) {
secretPasswords.splice(index, 1);
}
}

Changes made to a value stored in a variable will not be persisted between page loads. That's just a fundamental principle of JavaScript and web browsers. If you want to preserve state between page loads you are going to need to use cookies or localStorage.

Related

Why browser does not see local storage elements' values?

I am creating a simple Tetris game using React JS. My main Component besides App.js is a Tetris.js functional component. In useEffect() I am storing components like the stage or current player tetromino using Local Storage. While playing, retrieving data in the console is possible and the data is not null.
useEffect(() => {
localStorage.setItem("dropTimeStored", JSON.stringify(dropTime));
localStorage.setItem("stageStored", JSON.stringify(stage));
localStorage.setItem("playerStored", JSON.stringify(stage));
localStorage.setItem("rowsClearedStored", JSON.stringify(rowsCleared));
localStorage.setItem("scoreStored", JSON.stringify(score));
localStorage.setItem("rowsStored", JSON.stringify(rows));
localStorage.setItem("levelStored", JSON.stringify(level));
localStorage.setItem("gameOverStored", JSON.stringify(gameOver));
}, [dropTime, stage, player, rowsCleared, score, rows, level, gameOver])
I would like to give users a choice to continue the game after instantly closing the browser. Thats why in starting game function i am doing:
const startGame = () => {
console.log(loadLocalStorage);
if (loadLocalStorage){
setDropTime(JSON.parse(localStorage.getItem("dropTimeStored")));
setStage(JSON.parse(localStorage.getItem("stageStored")));
player = JSON.parse(localStorage.getItem("playerStored"));
rowsCleared = JSON.parse(localStorage.getItem("rowsClearedStored"));
setScore(JSON.parse(localStorage.getItem("scoreStored")));
setRows(JSON.parse(localStorage.getItem("rowsStored")));
setLevel(JSON.parse(localStorage.getItem("levelStored")));
setGameOver(JSON.parse(localStorage.getItem("gameOverStored")));
} else {
localStorage.clear();
setStage(createStage());
setDropTime(1000);
resetPlayer();
setGameOver(false);
setScore(0);
setRows(0);
setLevel(0);
}
}
But while the "loadLocalStorage" flag is set to True, which means that the user has clicked the button and is willing to continue the game, nothing has happened. Elements retrieved from local storage are empty, for example the stage has no elements - JSON.parse(localStorage.getItem("stageStored")) gives me empty stage, with no tetrominoes. Why it is happening? Is closing browser or closing browser's card flushes localStorage? Thanks.
Move your localStorage.setItem() calls from useEffect block. For each app refresh, calling setItem in useEffect is overriding the actual storage values.
For this to work, set your local storage data whenever you are updating the state.
For Example, write a common method to update the localStorage data like this :
const updateLocalStorage = (key, value) => {
localStorage.setItem(key, value);
}
Whenever you are updating the state like below, immediately set the localStorage value as well :
const dropTime = 1000 / (level + 1) + 200;
setDropTime(dropTime);
updateLocalStorage('dropTimeStored', dropTime);
As an example, I have done this change in your code for dropTime value in your pastebin code. You can do the same for other values as well.

Variable Resets to 0 every refresh

I'm trying to make a code which lets me show how much a certain part of my website has been views.
My problem is, when I fresh refresh, it goes back to zero, instead of 2. I hope you can help me out. I want the code to run forever, or as long as I want it to, and it will just add a 1 to what it has been, even if it was yesterday. Here's the sample of the code.
<script type="text/javascript">
var bannerViews = 0;
function addViews (){
bannerViews = bannerViews + 1;
}
addViews();
</script>
<p>This banner has been viewed <script type="text/javascript">document.write(bannerViews);</script> timesĀ </p>
Hope you can help me out.
It is because every time you refresh your page, your code reinitializes. In-order to persist the data, you need to store it somewhere. Either in a cookie or a localstorage.
If you go ahead with the localstorage, here's how you do it.
var bannerViewCount = localStorage.getItem('bannerViews');
if(!bannerViewCount) {
bannerViewCount = 0;
}
function addViews() {
localStorage.setItem('bannerViews', ++bannerViewCount);
document.body.innerHTML = 'Banner view count is :' + bannerViewCount;
}
addViews();
Demo (click on Run on the top bar multiple times and see it incrementing)
Here, what am doing is first, fetching the banners view count. If I don't get it, I initialize it with zero.
Later, I on addViews() call, I increment the bannerViewCount by one and store it to the localStorage. That's it.
Note that the data is stored in your local storage, so if you are expecting that the count should be visible to other users too, you need to store it in a database or a text file and later parse it.
If you want to store it on the cloud, so that you can share the count across the visitors, you can do something like this.
function addViews() {
$.get('//jsonbin.io/b/5974382ca489d40388582791/latest', function(data) {
var bannerViewCount = data.bannerviews;
$.ajax({
url: '//jsonbin.io/b/update/5974382ca489d40388582791',
type: 'post',
dataType: 'json',
data: {
snippet: JSON.stringify({
bannerviews: ++data.bannerviews
})
},
success: function(fetch) {
var data = fetch.data;
document.body.innerHTML = 'Banner view count is : ' + JSON.parse(data).bannerviews;
}
});
});
}
addViews();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click on "Run Code Snippet" button and see the counter incrementing. Go to any other browser and the count will persist as expected. Note that the data stored here can be manipulated as there is no authentication in place. So avoid it if you want the count to be precise and legit.
It goes back to 0 because the variable bannerViews is reinitialised to 0 on every page load.
You will need to store this variable in a JSON file/DB and fetch/update the value there.
Every time you refresh the page the code is going to be reset and variables are included.
To solve this you have to either use a web server and have the variable saved there or find a way to save the variable to the filesystem and load it
back.
The reason the counter is reset constantly is because you're declaring the variable during runtime. There is no persistence to the variable so every time the website is loaded, the variable starts against from 0. Each browser client would keep track of the variable separately so even if you were able to get the variable to persist on your local browser, you would not be able to keep track of the page views from other browsers. The solution to this problem is to keep track of the page views from a centralized server.
You can use a free service such as http://www.webestools.com/pages-views-counter-free-number-pages-views-statistics.html to create the counter that would persist between page views and different clients.
What you need to do is to get the initial value 0 , store in on the server , database or file.
change line var bannerViews = 0; to something like;
var bannerViews = getValueFromServer();
and every after re assigning it, you store it back to the external storage;
For now everytime you refersh the page .
the code var bannerViews = 0; will run and hence bannerViews will alwayz be re assigned to 0

using localstorage to keep html on page refresh not working

I'm trying to integrate this fiddle: http://jsfiddle.net/jaredwilli/ReT8n/ in a fiddle I'm doing:
https://jsfiddle.net/vlrprbttst/99c8gn7k/
Basically you have a basket with some items inside of it, you can add or remove them. What I want is that, on page refresh, the html() of the .basket is kept in local storage. I'm stuck here:
https://jsfiddle.net/vlrprbttst/z8cffk4c/
I've put the forLocalStorage variable in the click handler because otherwise, the var wouldn't update itself but now I'm guessing that the final local storage code
if(localStorage.getItem('toDoData')) {
forLocalStorage = localStorage.getItem('toDoData');
}
is not working because it can't retrive the variable?
I've tried moving around things but I'm stuck here. what am i doing wrong?
You need to update DOM once your variable is set, e.g:
// LOCAL STORAGEEEEEEEE
if (localStorage.getItem('toDoData')) {
forLocalStorage = localStorage.getItem('toDoData');
$('#cart').html(forLocalStorage);
itemsCount();
}
Local storage can only store string key value pairs. I ensured you are passing in a string and also added a function to populate the cart on refresh, which resolved problems.
function populateCart() {
var items = localStorage.getItem('toDoData') || '';
$('#cart').html(items);
}
Added this call inside document.ready, like so: -
$(document).ready(function() {
populateCart();
// rest of code
});
Working CodePen: http://codepen.io/owenayres/pen/oxKmZg
You can do some light reading here on local storage. It is, in my opinion, best practice to store the data for the HTML as some JSON in local storage, which you would then loop through and regenerate the HTML for when reading this data again.

Keeping JS changes on DOM after refresh

So, I have this weird thing going on in my test site, where I have every "link" (be it menu,button, or anything) to show/hide divs instead of loading pages. Pretty basic right? Except whenever I refresh the page, it all reverts back to the Homepage, which is expected. Based on my search for answers, I think I have to use the local/session storage option. Session sounds better.
So here's the deal. I looked up the w3schools page on sessionStorage and I get how it works, but I don't undestand how I could apply this to my page. Basically every link on my page runs a function that hides the previous div and shows a new one with the content. So I was thinking if every time a function triggered, it would store a value on a var that would appoint the function as the last used. Then somehow use sessionStorage and make it work, but I can't built it. Any help?
Here's a short example of my current code.
EDITED
var state = null;
function show1() {
state = "home";
"use strict";
document.getElementById('snow').style.display = "block";
document.getElementById('btn').style.display = "none";
}
function ramble() {
state = "ramble";
"use strict";
document.getElementById('ramble').style.display = "block";
document.getElementById('snow').style.display = "none";
document.getElementById('tex').style.display = "none";
}
That's basically it.Onclick show/hide.
You can use the following syntax:
Save data:
sessionStorage.setItem('key', 'value');
Retrieve data:
var data = sessionStorage.getItem('key');
More info and examples: https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
The same goes with localStorage, but with the persistance differences you already found
I hope my solution will help you: If you want to keep your JS changes, you need to save them to database using AJAX and also change page architecture and logic to use data from database. After that, even if you reload page you will keep all your changes.

Javascript storing data

Hi I am a beginner web developer and am trying to build the interface of a simple e-commerce site as a personal project.The site has multiple pages with checkboxes.
When someone checks an element
it retrives the price of the element and
stores it in a variable.
But when I go to the next page and click on new checkboxes products the variable automaticly resets to its original state.
How can I save the value of that variable in Javascript?I am using the jQuery library.
EDIT:This is the code I've writen using sessionStorage but it still dosen't work when I move to next page the value is reseted.
How can I wright this code so that i dosen't reset on each page change.All pages on my website use the same script.
$(document).ready(function(){
var total = 0;
$('input.check').click(function(){
if($(this).attr('checked')){
var check = parseInt($(this).parent().children('span').text().substr(1 , 3));
total+=check;
sessionStorage.var_name=0 + total;
alert(sessionStorage.var_name);
}else{
var uncheck = parseInt($(this).parent().children('span').text().substr(1 , 3));
total-=uncheck;
}
})
The syntax for sessionStorage is simple, and it retains it's data until the browser window is closed. It acts exactly like any other javascript object. You can use dot-notation or square bracket notation (required for keys with spaces) to access stored values.
Storing values using sessionStorage
sessionStorage['value key'] = 'value to store';
Using stored values
alert(sessionStorage['value key']); // Alerts "value to store".
You could use localStorage to acomplish this. You'd need to set up a fallback for it, using localStorage however could be done like this:
Reading from storage:
if (localStorage['valueName'] !== undefined) {
input.value = localStorage['valueName'];
}
Writing to storage:
localStorage['valueName'] = input.value;
Here's a jsfiddle example: http://jsfiddle.net/yJjLe/
As already mentioned above you can use sessionStorage or localStorage. Another option available is HTML5 Web Databases
And take a look at this presentation.
Also keep in mind that html5 web storage is not secure as anyone can see your stored data simply from the console.

Categories