Html local storage saving data - javascript

I have a simple main menu program.
HOW IT WORKS:
Simple, once you click level one and click on the done button, it unlocks level two, the problem is when you refresh the page it does not save it and level two is gone again.
Code I've tried:
I tried HTML Local storage, here are some examples I used
window.highestLevel = localStorage.getItem('highestLevel');
and stuff like that but I can't get it to save the level.
Please help here is a link. jsFiddle
Note: I want to use html local storage.

Save it with
window.localStorage.setItem('highestLevel', window.higestLevel);

Make sure you check that the browser you are working with supports localstorage. You could use Modernizr or something to do that easily.
To set something in localstorage:
javascript
localStorage.setItem('your-identifier', your-data);
So for example, to save a user's name:
javascript
localStorage.setItem('username', 'Luke Skywalker');
To get "username" back from localstorage:
javascript
localStorage.getItem('username');
Hope this helps!

You'll need to use getItem (as you did in your question) when you load the page, and hide level 2 as needed:
if (localStorage.getItem("highestLevel") <= 1) {
$("#level2").hide();
}
You'll also need to setItem to save when the user gets to level 2:
function mainMenuLvl2() {
localStorage.setItem("highestLevel", 2)
$('#level2').show();
}
Here's a JSFiddle: http://jsfiddle.net/ptcbkamx/2/

You can use localStorage and sessionStorage to store your data on client side like below
localStorage.setItem("variablename","value"); //--> this value is object type anything
var storedValue = localStorage.getItem("variablename");
or
sessionStorage.setItem("variablename","value");
var storedValue = sessionStorage.getItem("variablename");

You can use:
localStorage.setItem("highestLevel", window.highestLevel);
Then, if you want to get the highest level, use this:
localStorage.getItem("highestLevel", window.highestLevel);
I hope this helped!

Related

How to save html data local

How can I save my HTML element tag data after user closed the browser. For example
<div class="classOne" data-random="50">
And i used jQuery to change the data attribute
$(".classOne").attr("data-random","40")
And if the user close out the browser and comes back the value for data-random will be 40. How can I achieve this ?
Have you tried looking at localStorage?
LocalStorage allows you to store data within the browser. So even after the user close out the browser and comes back, you still have the value stored in your LocalStorage
Here is a sample code on how you can use local storage:
localStorage.setItem("data-random", 40);
You can set it with:
localStorage.setItem("data-random","40")
And later load it:
localStorage.getItem("data-random")
If you want to store JSON objects, you should use stringify() before saving and JSON.parse() after loading.
try localStorage.
https://developer.mozilla.org/ko/docs/Web/API/Window/localStorage
$(document).onload(function(){
if(localStorage.rendomData){
var data = localStorage.rendomData - 10
localStorage.set(randomData,data)
}
else{
localStorage.set(randomData,50)
}
})
I hope this helps.
The easiest way to achive it is to use cookies. Just take this plugin: https://github.com/carhartl/jquery-cookie and then above the line:
$(".classOne").attr("data-random","40")
add:
var randValue;
if (typeof $.cookie('my-rand-value') == undefined) {
// generate random value
randValue = generateRandomValue //assign random value to variable
$.cookie('my-rand-value', randValue)
}
else {
randValue = $.cookie('my-rand-value')
}
at the end change static value to your variable:
$(".classOne").attr("data-random",randValue)
You can do that by using cookies as well as by using local storage -
for local storage first store first try to get value if it is stored like -
if(localStorage.getItem("data-random") != null){
return localStorage.getItem("data-random");
} else {
return 50;
}
and when user changes the value you can save that value by -
localStorage.setItem("data-random", value);
Use Jquery function beforeunload and save it into localStorage.
$(window).on('beforeunload', function() {
// Put the object into storage
localStorage.setItem('data', $(".classOne").attr("data-random"));
});
To Retrieve the data from storage whenever your page opens.
var retrievedData = localStorage.getItem('data');

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.

Saving user edited Timeline?

I've been playing around with http://almende.github.com/chap-links-library/timeline.html which allows the user to add/edit/delete events on the timeline. Closing or refreshing the browser resets it to the pre-loaded data source - JSON, table info or Google Spreadsheet. Nothing the user adds or changes is saved.
How do you make user changes persistent?
I've used HTML5 localStorage before for saving text, checkbox, and select box entries, etc. but with this Timeline the only entry is:
div id="mytimeline"
which has a script associated with it:
// Instantiate our timeline object.
timeline = new links.Timeline(document.getElementById('mytimeline'));
which is the reference to the JS that builds the timeline container.
Any ideas or examples or pointers?
Thanks.
Update:
Here is what I have so far:
//Check to see if localStorage is supported
var db = getLocalStorage() || alert("Local Storage Not supported in this browser. Try updating to the latest Firefox, Chrome or Safari browsers.");
function getLocalStorage() {
try {
if(window.localStorage ) return window.localStorage;
}
catch (e)
{
return undefined;
}
}
//Store Timeline Data to localStorage
function storeTimelineData(){
var data=timeline.getData();
localStorage.setItem('mytimeline', JSON.stringify(data));
var storedData=JSON.parse( localStorage.getItem('myTimeline') );
// clear storage
function clearLocal() {
clear: localStorage.clear();
return false;
}
I've also made these changes - body onload="storedData()" to try to load localStorage saved values and changed div id="mytimeline" onmouseup="storeTimelineData()" to store the values when changes are made to the timeline.
Changes to the Timeline are being saved in localStorage and I can see these changes in the console for Key/Values. When I refresh the browser though, these are not being loaded into mytimeline. What did I miss?
Thanks.
I've never seen plugin until your post but in the API docs are all sorts of methods. The most important one you would need to start would be getData().
Simplest storage scenario would be to set up a timed interval to get the data , convert it to JSON and store it. Alternative would be to update your stored data every time use interacts with events.
A basic storage update function would be along the lines of:
function storeTimelineData(){
var data=timeline.getData();
localStorage.setItem('myTimeline', JSON.stringify(data));
}
Then when page loads you would need to check if there is data in localStorage , convert it to a javascript object using :
var storedData= JSON.parse( localStorage.getItem('myTimeline') );
And use this data to initialize the plugin if the data exists.
I have really just given you a basic overview. There are numerous details you will have to sort out from here

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