How to save html data local - javascript

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');

Related

Sending parameters with history.back()?

Is it possible to send a track/api variable to the next cmp, while using history.back() in LWC.
this.var1 = false;
var compDefinition = {
componentDef: "c:Component-to-navigate",
attributes: {
leadId: this.SomeLeadId,
SomeId: this.SomeId,
Variable-To-send: true
}
};
var encodedCompDef = btoa(JSON.stringify(compDefinition));
this[NavigationMixin.Navigate]({
type: 'standard__webPage',
attributes: {
url: '/one/one.app#' + encodedCompDef
}
});
Instead of this i want to use history.back(), and also need to pass ' Variable-To-send' with this is this even possible ? tried directly with onclick funtion, not working.
Apart from navigation any other way ? basically i dont want to reload the previous page. ? tried history.back(), windows.location = etc, but not able to pass the same..
Please help with the approach if possible thanks.
well, history.back() method loads the previous URL (page) in the history list and only works if a previous page exists.
So, we cannot set any parameter while calling the history.back().
However, we can simulate the same thing by using some temporary storage that can store the parameter value that we want to communicate to the other component between the pages.
to do so we can either make use of:
local storage
session storage
cookie
or any other storage place where we can keep the data and access :)
Example:
we can use local storage like below:
// to set the param value
localStorage.setItem('param1', 'value1');
localStorage.setItem('param2', 'value2');
// going back or any navigation
history.back();
// to get the value at any other place
const param1 = localStorage.getItem('param1');
const param2 = localStorage.getItem('param2');
// to remove the data from storage
localStorage.removeItem('param1');
localStorage.removeItem('param2');
// or
localStorage.clear();

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.

Displaying Array Values From Local Storage

I am trying to display the values that have been stored in an array within local storage. I have been able to store the values in local storage and add other values on the click of a button but I cant retrieve the values back out and display them on a page.
This is my code that adds values to local storage.
$("#player1Link").click(function() {
if (localStorage.getItem("player1Favourite") !== null) {
var a = JSON.parse(localStorage.getItem('player1Favourite'));
if (a.indexOf(chosenPlayerId) === -1) {
a.push(chosenPlayerId);
localStorage.setItem('player1Favourite', JSON.stringify(a));
alert("Pushed in");
} else {
alert("Already in favourites");
}
} else {
var a = [];
a.push(chosenPlayerId);
localStorage.setItem('player1Favourite', JSON.stringify(a));
}
})
I want to be able to click a button to retrieve the values and display them on the page but I can figure out the code to go in this function.
$("#playerRetrieve").click(function() {});
If anyone could help it would be much appreciated.
I made a jsfiddle, it seems to work there: jsfiddle
try:
localStorage.getItem('player1Favourite');
or:
localStorage.player1Favourite
You might want to have a look at:
this topic
or at
Mozilla
I'm not exactly sure I understand you correctly, because if you just want to retrieve the values you can use the same code, just remove the insertion from your code and change the jQuery selector.
$("#playerRetrieve").click(function() {
if (localStorage.getItem("player1Favourite") !== null) {
var a = JSON.parse(localStorage.getItem('player1Favourite'));
// Do what you want with the values, which are now in a.
}
});

Html local storage saving data

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!

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