Tips for retaining the previous positions of sliders post page refresh

Currently, I have a network visualization project created with d3 and angular. You can view the visualization by following this link. I'm interested in saving the last state of the network so that even after refreshing the page, it will display the same setup. However, I am unsure of how to achieve this.

I've read about using either `sessionStorage` or `localStorage` for this purpose, but I'm struggling to implement it in my visualization project.

My attempt involved storing JSON data in sessionStorage like so:

 if (sessionStorage) {
        sessionStorage.setItem("myKey", myJSON.toString());
    }

 if (sessionStorage) {
        sessionStorage.getItem("myKey"); // {"myKey": "some value"}
    }

I also tried a similar approach using localStorage:

localStorage.setItem("networkGraph", networkGraph);
var networkGraph = localStorage.getItem("networkGraph");

Unfortunately, these methods did not work as intended. Can anyone confirm if this is the correct way to accomplish my goal?

Your assistance on this matter would be greatly appreciated!

Answer №1

Have you considered using localStorage instead of sessionStorage? With sessionStorage, any saved data will be erased when the browser tab is closed.

In your onChange function, you can use

localStorage.setItem('inputLayerHeight', vm.inputLayerHeight);
to store the value of inputLayerHeight. Then, retrieve it with
Number.parseInt(localStorage.getItem('inputLayerHeight')) || 15
to set the value at the value property of the vm.inputLayerHeightSlider object. This method can also be applied to other values that need to be retained.

Answer №2

You're so close to getting it right! Just make a small tweak with how you're using localStorage. All you need to do is include the window or $window (a more 'angulary' approach to accessing the window variable) variable in your code like this:

$window.localStorage.setItem("networkGraph", JSON.stringify(networkGraph));

By the way, have you checked out angular-storage? It's a great tool for simplifying local storage operations and making your life easier :)

Answer №3

The issue might be stemming from how data is being stored in your local storage. Currently, you are saving the data as a string, which d3 may not recognize as valid data options. To resolve this, consider the following approach:

if (localStorage) {
    // Convert the stored data into a JavaScript object
    const data = JSON.parse(localStorage.getItem("myKey"));
} else {
    // Fetch the data...
    // Store it in either sessionStorage or localStorage
   localStorage.setItem("myKey", myJSON.toString());
}

You can adjust the logic based on your needs, but the key point is to use JSON.parse() when retrieving data from storage.

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

Changing SVG containing image tags into HTML canvas

I'm attempting to convert an SVG file to an HTML canvas, and everything works perfectly until I introduce the image element in the SVG. When I include image elements, the canvg function stops working. Below is the code I used to convert the SVG to ca ...

How does Express handle the req.params format?

Encountering a strange issue with req.params in Express. When accessing specific properties like res.json(req.params.paramName), it returns the expected value. But when attempting to send the entire req.params object to the client using res.json(req.params ...

Attempting to send numerous identifiers in an API request

I encountered a problem while working on a function in Angular that involves pulling data from an API. My goal is to enhance a current segment to accommodate multiple IDs, but I face difficulties when attempting to retrieve more than one ID for the API que ...

Ways to extract a Bearer Token from an Authorization Header using JavaScript (Angular 2/4)

When working with JavaScript, I have successfully implemented a method for authenticating to my server using an http post request. Upon receiving a response from the server, it includes a JWT in an Authorization header like this: Authorization: Bearer my ...

Using Spring Boot and AJAX to dynamically load content as users scroll down the page

Hi there! I've been running into some issues with Spring Boot and AJAX. Currently, I have buttons that need to be clicked in order to navigate to another page (next, previous). I'd like to use an AJAX request instead to load my page when scrollin ...

Issue finding a route based on dates

Hey everyone, I'm working on a feature where I need to fetch tasks made by a user within a specific date range provided by the user. However, I am facing some issues with getting the date and routing it. Here is the URL format that I am trying to work ...

Whenever I press the button, the table content disappears mysteriously

Objective: The main goal is to hide all the table bodies initially. Upon clicking the arrow button, the respective table body should be displayed. Challenge Faced: Encountering difficulty in hiding the table bodies initially. Additionally, only the last ...

What is the best way to retrieve a list of unchecked checkboxes in a Razor Page model?

Currently, I am working on a razor page using .NET Core 7. I have encountered an issue where I am unable to pass values of 1, 2, and 3 for unchecked checkboxes from the HTML page to the page model in the post method. When the user clicks the submit button ...

The error message "Unable to execute stripe.customers.createBalanceTransaction function" is displayed on

Having trouble with a Type Error while attempting to use stripe's createBalanceTransaction function. You can find the API reference for the function here: https://stripe.com/docs/api/customer_balance_transactions/create The error message being receiv ...

What is the best way to finish up the JavaScript code below?

Having just started learning JavaScript, I am struggling to figure out how to use JavaScript to clear the text in a text box and move it below the box when a user starts typing. I've been watching this tutorial http://codepen.io/ehermanson/pen/KwKWEv ...

What is the best way to toggle the color of the circle div in the center between yellow and white with every click within the circle?

Up to now, I have successfully accomplished this with just one click. I deleted the lightbulb image const sphere = document.getElementById("sphere"); sphere.addEventListener("click", event => { console.log("You clicked the ...

How can I customize an SVG using CSS when it's being accessed from another directory on my computer?

I find myself in a bit of a bind at the moment. Within my code lies an SVG depicting a map of the United States. Upon clicking on a specific state, the entire country fades away, revealing a separate SVG displaying only that state. Each of the 50 states is ...

When using express, encountering a "Cannot GET / on page refresh" error

Currently working on a small MERN stack project. Managed to deploy it on Vercel successfully and the application runs as expected. Navigating to "/classes" and "/students" using the buttons in the browser works fine, however, upon reloading those pages I e ...

Encountering surprising outcomes with jQuery AJAX POST functionality when interacting with PHP script

I have created a form where I am expecting to receive post results in my div with the ID "response". <!DOCTYPE html> <html> <head> <title>AJAX POST</title> <script src="jquery.js"></script> <script> $(do ...

How does the performance of setTimeout in nodejs compare?

Currently, I'm developing an Angular application with Node.js Express as the backend. The Angular app fetches database rows in JSON format and displays them. However, the AJAX requests are being made too quickly by users, causing a strain on the serve ...

Differences between typical functions and function variables in JavaScript

Can someone clarify the distinction between function MyFunc() { // code... } and var MyFunc = function() { // code... }; when it comes to JavaScript? ...

Do identical files stored in separate locations produce unique sha1 hashes?

var crypto = require('crypto'); var fs = require('fs'); var file1 = process.argv[2]; var file2 = process.argv[3]; var sha1sum = function(input){ return crypto.createHash('sha1').update(JSON.stringify(input)).digest(' ...

React - Incorrect components experiencing style changes due to setTimeout

Check out the code snippet here: https://jsfiddle.net/69z2wepo/204131/ A main component displays two 'notifications' each with different disappearance timings. class Page extends React.Component { constructor(props) { super(props); t ...

Tips for accessing distinct ng-model values within ng-include within a single HTML document

Consider the following scenario with two HTML files: index1.html <input type="text" ng-model="model.Name"> <!-- Some complex form !--> index.html <div>Journalist's Details: Name:<div ng-include="index1.html"></div> ...

How can we enhance the backbone sync feature by appending a query string to the URL?

I am facing an issue with adding a token to the backbone URL query string and I am seeking assistance from you all. Here are three important things to note: There is a REST API that requires a token for each request An NGINX backend handles authenticatio ...