Saving an item using localStorage

I've been struggling to figure out how to make localStorage save the clicks variable even after refreshing the browser.

Initially, I attempted using JSON.stringify and JSON.parse but later discovered that using parseInt could be a more suitable option since I only need to store a number.

As someone new to programming, I found most examples to be either too complex, poorly explained, or outdated. Hopefully, you can provide some guidance as I've been trying to resolve this issue for over a week now.

For context, I'm working with Phaser 2.5.0 on MAMP with Google Chrome v49.0.2623.112 (64-bit) on OS X 10.8.5.

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update });

var scoreText;
var clicks = 0;



function preload() {

    game.load.image('clickBox', 'assets/ClickMe.png');
    game.stage.backgroundColor = '#182d3b';
    game.stage.disableVisibilityChange = true; 
}


function create() {

    localStorage.setItem('clicks', parseInt('clicks'));
    localStorage.getItem('clicks');

    button = game.add.button(game.width/2, game.height/2, 'clickBox', upScoreText);

    scoreText = game.add.text(30, 30, "CLICKS: " + clicks, {font: "20px Arial", fill: "#ffffff", align: "left"});

    button.scale.x = 0.5;
    button.scale.y = 0.5;
    button.anchor.setTo(0.5);
    button.inputEnabled = true;
}


function update () {
            scoreText.setText("CLICKS: " + clicks);        
}


function upScoreText () {
    clicks++;
}

Answer №1

It is recommended not to store the literal clicks, but rather to store the variable with that name. Additionally, there is no need to use parseInt on clicks, as it is already a number. Keep in mind that localStorage stores everything as a string, so regardless of what you do, it will ultimately be stored as a string.

When storing:

localStorage.setItem('clicks', clicks); // always stored as a string

When reading:

clicks = +localStorage.getItem('clicks'); // `+` converts it back to a number

It's important to place these statements correctly. Writing a value to storage and immediately reading it back out serves no purpose since the value remains unchanged. It would be more efficient to skip those two lines...

Instead, read the value once in the create function, and update the value whenever it changes, such as in the upScoreText function:

function create() {
    // Load. If the value doesn't exist in localStorage, set it to 0. 
    // Otherwise, convert it to a number using `+`:
    clicks = +localStorage.getItem('clicks') || 0;
    // etc...
}

function upScoreText () {
    clicks++;
    // Save:
    localStorage.setItem('clicks', clicks);
}

By following this approach, you'll maintain an incrementing clicks variable that persists through page reloads. However, you may want to include a method to reset the value back to 0 when needed.

Answer №2

You are using parseInt incorrectly, for example instead of

localStorage.setItem('clicks', parseInt('clicks'));

You should use

localStorage.setItem('clicks', parseInt(clicks));/*removed the quotes for the clicks*/

I also suggest checking if the clicks variable exists in localStorage before assigning it to a variable. You can implement it like this:

var clicks=localStorage.getItem("clicks")||0;

Not sure if this is what you were looking for though :/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on disregarding events within an html table

I have a see-through table with a width set to 100% that houses various HTML content. I am utilizing the table to properly center a particular element on the screen. However, the table is intercepting mouse events and preventing users from clicking on lin ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

Initiate a fresh start with an automatic input reset

When you perform an action in the first id = "benodigheden", I believe there should be a specific outcome that then triggers a second rule for id = "benodigheden". However, I have been unsuccessful in finding information on this topic online. It seems like ...

Selecting properties from a GeoJSON object on the fly with Leaflet

I am currently attempting to dynamically modify the displayed property on my leaflet map. Below is the code I have been working with: $("#button_thermal").click(function(){ $.getJSON("physicalProperties.geojson", function(data) { var geojson2 = L.geoJson( ...

Retrieve information from the existing URL and utilize it as a parameter in an ajax request

Currently, I am working on a website with only one HTML page. The main functionality involves fetching the URL to extract an ID and then sending it to an API using an AJAX call. Upon success, the data related to the extracted ID is displayed on the page. H ...

Pop-up windows, the modern day digital version of fortune cookies

Expressing my requirement might be a bit challenging, but I will do my best. My goal is to create a web application using ASP.Net with C#. This project calls for functionality similar to the Windows popup: When a user clicks on the favorite button in IE- ...

What is the best way to create a universal variable that can be accessed across all routes in an Express/

Exploring the world of nodejs and express, I have turned to the Parse API for my backend database needs. At the moment, I have an ajax post triggered on page load to one of my routers /getuser, which retrieves the current user if they are logged in. I am ...

Tips for retrieving multiple data outputs from an ajax success function

Within my project, I have two separate JavaScript files named myJs1.js and myJs2.js. One of the methods in myJs1.js is invoking a method from myJs2.js. My goal is to retrieve the values r1 and r2 into the results (within myJs1.js). I attempted to achiev ...

Listener document.addEventListener (function() {perform the function as shown in the illustration})

Currently facing an issue that I'm struggling to resolve, attempting to execute a code snippet from the ngcordova website without success. While using the plugin $cordovaInAppBrowser.open ({... it generally functions well until the inclusion of the ...

Having an excess of 32 individual byte values

My current project involves developing a permission system using bitwise operators. A question came up regarding the limitation of having only 32 permissions in place: enum permissions { none = 0, Founder = 1 << 0, SeeAdmins = 1 << ...

Preventing Jquery Append from Adding Previous Elements

I am struggling to figure out how to display the star rating for each hotel individually. I have 5 hotels, each with a different star rating. Here is my Javascript code: function GetStarHotel() { var parent = $(' p.star '), imagePat ...

How can you switch the display between two different class names using JavaScript?

I currently have a total of four filter buttons on my website, and I only want two of them to be visible at any given time. To achieve this, I labeled the first set of buttons as .switch1 and the second set as .switch2. Now, I've added a 'switch ...

Priority is given to strings over numbers

Here's some code I'm working with: <tbody> <tr> <td class="float-left"> <!-- {{selectedTemplat?.modifiedAt | da ...

How to best handle dispatching two async thunk actions in Redux Toolkit when using TypeScript?

A recent challenge arose when attempting to utilize two different versions of an API. The approach involved checking for a 404 error with version v2, and if found, falling back to version v1. The plan was to create separate async thunk actions for each ver ...

What is the best way to generate a new object within a function and then return it

The function performs the following steps: Retrieves an XML document through AJAX. Identifies relevant information within the document. Dynamically converts it into an object using a for loop. How can I access this generated object outside of the functi ...

Utilizing Node.js and Express.js to Parse HTML Form Inputs

Having trouble extracting input from an HTML form and utilizing it in Node.js. Here is the HTML form being used: <form action="/myform" method="POST"> <input type="text" name="mytext" required / ...

Using Javascript, delete all chosen HTML elements containing innerText

Looking to extract certain HTML tags from a block of code in TextArea1 and display the modified output in TextArea2 upon clicking a button. <!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8&quo ...

Ways to verify the element prior to the completion of the request?

Utilizing Angular and Playwright Within my application, I have incorporated 2 buttons - one for delete mode and another for refreshing. Whenever the user triggers a refresh action, the delete mode button is disabled. Once the request returns, the delete m ...

Identifying edited files within the node_modules directory: A comprehensive guide

While working with the serverless framework, I installed it using npm. During my debugging process, I made some modifications by adding console.log statements to different files within the node_modules folder. Unfortunately, I can't recall which speci ...

A guide on incorporating router links within a list component in a React project

In one of my projects, I've implemented a navbar with a profile icon that expands to show four different options: "Log in", "Register", "Edit", and "Admin". However, I'm facing an issue where clicking on these links doesn't always redirect m ...