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

Determine the current iteration index within recurring tasks using BullJS

When working with repeatable job callbacks, I often need to perform specific actions at a certain point in the script. For instance: const Bull = require('bull'); const queue = new Bull('payment'); // This task should run every 5 minut ...

I've been encountering a recurring issue of receiving NaN followed by a number in React. Any suggestions on how to resolve

click here to see the image const number = parseInt(props.detail.price,10) const toLocale = number.toLocaleString("ko-KR") console.log(toLocale) return ( <div> <Descriptions title="Product ...

Retrieving checkbox data and transmitting it without using a form submission

I've been attempting to extract values from a checkbox group, but for some reason, it's not working as expected. Here is the approach I'm taking: Using a loop to generate checkboxes <input class="group1" type="checkbox" name="catCheck" ...

What are the steps to establish a Z-axis coordinate system in three.js?

When working with three.js, the Y axis typically represents up and down, while the Z axis represents forward and backward. However, I want to switch this so that the Z axis represents up and down, and the Y axis represents forward and backward. Here is an ...

Changing a class using JavaScript: Adding and removing class dynamics

Currently, I am attempting to create a function that will toggle the visibility of a visual object on and off whenever the user clicks on it. Additionally, I need to implement a click event listener within the HTML class named btn-sauce. Unfortunately, my ...

"Vue is failing to actively update an input that relies on changes from another

I am working on a project where the selected country automatically determines the phone country code. I have set it up so that when I change the country, the corresponding country code should update as well. Within a customer object, both the country and ...

Can we modify the styling of elements in Angular based on an object property?

I have a class named Task with the following properties: export class Task { name: string; state: number; } Within my component.ts file, I have an array of objects consisting of instances of the Task class (tasks). When displaying them in the tem ...

Parsing improperly formatted JSON from an HTTP GET request can be done using either AngularJS or JQuery

Trying to decipher a poorly formatted JSON response from a remote server that looks something like this: //[ {},{} ] In my AngularJS code: $http.get('http://www.example.com/badjson') .success(function(data) { console.log(data); }) ...

Prisma encountered an error with the database string: Invalid MongoDB connection string

I'm encountering an issue with my MongoDB data provider, as I am informed that my connection string is invalid. The specific error message states: The provided database string is invalid. MongoDB connection string error: Missing delimiting slash betw ...

What is the best way to determine if a child div exists within a parent div?

Is there a way to determine if any div exists within the parent div? In my current scenario, I am adding two divs inside the parent div like this. $('#realTimeContents').append("<div style='width:22%; float: left; font-size:18px; line- ...

What is the best way to include arrays in VueJS?

Currently, I am working with two arrays in my Vue application. The first array called desserts lists all the desserts that I have. The second array, moreDesserts, displays checkboxes with values. When a user selects a checkbox, the value is added to the se ...

Assign a title property in Vuejs only if the returned data from binding evaluates to true

Just starting out with vuejs and I have a question. How can I set the title based on a value returned from a specific method only if this value is true? Below is my code snippet: <td v-bind="value = getName(id)" :title="value.age" > {{value.na ...

A method to use jQuery to replace newlines with commas in user input

Input Processing Challenge <input> Whenever there is multi-line text pasted into the input field, I need to replace newlines (\r, \n, and \r\n) as well as tabs \t with commas ,. This scenario mainly occurs when users copy c ...

How can I transfer a collection of JSON objects from JavaScript to C#?

Feeling a bit confused here. I have some Javascript code that will generate JSON data like the following: {type:"book" , author: "Lian", Publisher: "ABC"} {type:"Newspaper", author: "Noke"} This is just one example, I actually have more data than thi ...

Placing a moveable object in a designated spot for dropping at the desired location

I've been attempting to clone and drop a draggable object at the exact position within a droppable area where the drop event takes place. While I have come across examples online that demonstrate appending draggables to droppables, they all tend to re ...

Undefined Response Error when Utilizing Dropzone for File Upload in Express

I am currently in the process of setting up a basic image upload demonstration using Dropzone and Express. Here is what my form looks like: <form id="ul-widget" action="/fileupload" class="dropzone" enctype="multipart/form-data"> <div class="fal ...

Learn how to create a logarithmic scale graph using CanvasJS by fetching data from an AJAX call

window.onload = function() { var dataPoints = []; // fetching the json data from api via AJAX call. var X = []; var Y = []; var data = []; function loadJSON(callback) { var xobj = new XMLHttpRequest(); xobj.overrideMimeType("applicatio ...

Experiencing issues with connecting to jQuery in an external JavaScript file

My jQuery formatting in the HTML file looks like this: <!doctype html> <html lang="en"> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script> </head> < ...

Create a stylish navigation dropdown with MaterializeCSS

Incorporating the materializecss dropdown menu feature, I encountered an issue where only two out of four dropdown menu items were visible. Here is the HTML code snippet in question: <nav class="white blue-text"> <div class="navbar-wrapper con ...

Global asynchronous functionality can be enabled in JavaScript

Wouldn't it be convenient to have the option to enable async functionality in the global scope? This way, there would be no need to wrap all asynchronous operations within a function. I'm curious if this is achievable in browser JavaScript or per ...