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.
Related
Hello I am currently building a chrome extension that automates a website and on a html page I save the users checkout data using localStorage.
I then realized that you cant call local storage in a content_script
so what I did was this in the html page where I set and get the local storage.
this is what I use to save the users checkout info in the checkout html page for him to visually see and change when they want to:
var autofill = localStorage.getItem("checkout-info");
var filler = autofill.split(",");
$("#name").val(filler[0]);
$("#email").val(filler[1]);
$("#tel").val(filler[2]);
chrome.storage.sync.set({'autofiller': autofill}, function() {
});
the .val split is how I keep the data inside the inputs so the user can see it.
the chrome.storage is how I then take the data and call it later in the content_scripts file:
chrome.storage.sync.get(['autofiller'], function() {
});
checker = autofiller.split(",");
alert(checker[1], checker[2]);
and for some reason every time the alert part runs no matter what number it is it always alerts all the data not split with the commas.
Which is weird because the split works perfectly in the other file where I use localStorage.
I have also editet the file and tried this aswell:
chrome.storage.sync.set({
'info0': (filler[0])
'info1': (filler[1])
'info2': (filler[2])
'info3': (filler[3])
'info4': (filler[4])
'info5': (filler[5])
'info6': (filler[6])
'info7': (filler[7])
'info8': (filler[8])
'info9': (filler[9])
'info10': (filler[10])
'info11': (filler[11])
'info12': (filler[12])}, function() {
});
then in the content_scripts file tried this:
chrome.storage.sync.get(['info0', 'info1', 'info2', 'info3','info4','info5','info6','info7',
'info8', 'info9', 'info10', 'info11', 'info12'], function() {
});
alert(info0);
I also tried doing the set method without the () between the fillers and it also did not work. Can anyone help me Please?
Any advice on why the split isn't working?
There is a big difference between localStorage and chrome.sync: the first one is synchronous, and chrome.sync is asynchronous, which means you have to use a callback function to work with retrieved data.
It is a pretty rookie question. Please, check the answers to this question: How do I return the response from an asynchronous call?
In specifically to your case, all processing of a data should be inside the callback function:
chrome.storage.sync.get(['autofiller'], function (result) {
const checker = result.autofiller.split(',');
alert(checker[1], checker[2]);
});
I'm trying to make a code which lets me show how much a certain part of my website has been views.
My problem is, when I fresh refresh, it goes back to zero, instead of 2. I hope you can help me out. I want the code to run forever, or as long as I want it to, and it will just add a 1 to what it has been, even if it was yesterday. Here's the sample of the code.
<script type="text/javascript">
var bannerViews = 0;
function addViews (){
bannerViews = bannerViews + 1;
}
addViews();
</script>
<p>This banner has been viewed <script type="text/javascript">document.write(bannerViews);</script> timesĀ </p>
Hope you can help me out.
It is because every time you refresh your page, your code reinitializes. In-order to persist the data, you need to store it somewhere. Either in a cookie or a localstorage.
If you go ahead with the localstorage, here's how you do it.
var bannerViewCount = localStorage.getItem('bannerViews');
if(!bannerViewCount) {
bannerViewCount = 0;
}
function addViews() {
localStorage.setItem('bannerViews', ++bannerViewCount);
document.body.innerHTML = 'Banner view count is :' + bannerViewCount;
}
addViews();
Demo (click on Run on the top bar multiple times and see it incrementing)
Here, what am doing is first, fetching the banners view count. If I don't get it, I initialize it with zero.
Later, I on addViews() call, I increment the bannerViewCount by one and store it to the localStorage. That's it.
Note that the data is stored in your local storage, so if you are expecting that the count should be visible to other users too, you need to store it in a database or a text file and later parse it.
If you want to store it on the cloud, so that you can share the count across the visitors, you can do something like this.
function addViews() {
$.get('//jsonbin.io/b/5974382ca489d40388582791/latest', function(data) {
var bannerViewCount = data.bannerviews;
$.ajax({
url: '//jsonbin.io/b/update/5974382ca489d40388582791',
type: 'post',
dataType: 'json',
data: {
snippet: JSON.stringify({
bannerviews: ++data.bannerviews
})
},
success: function(fetch) {
var data = fetch.data;
document.body.innerHTML = 'Banner view count is : ' + JSON.parse(data).bannerviews;
}
});
});
}
addViews();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click on "Run Code Snippet" button and see the counter incrementing. Go to any other browser and the count will persist as expected. Note that the data stored here can be manipulated as there is no authentication in place. So avoid it if you want the count to be precise and legit.
It goes back to 0 because the variable bannerViews is reinitialised to 0 on every page load.
You will need to store this variable in a JSON file/DB and fetch/update the value there.
Every time you refresh the page the code is going to be reset and variables are included.
To solve this you have to either use a web server and have the variable saved there or find a way to save the variable to the filesystem and load it
back.
The reason the counter is reset constantly is because you're declaring the variable during runtime. There is no persistence to the variable so every time the website is loaded, the variable starts against from 0. Each browser client would keep track of the variable separately so even if you were able to get the variable to persist on your local browser, you would not be able to keep track of the page views from other browsers. The solution to this problem is to keep track of the page views from a centralized server.
You can use a free service such as http://www.webestools.com/pages-views-counter-free-number-pages-views-statistics.html to create the counter that would persist between page views and different clients.
What you need to do is to get the initial value 0 , store in on the server , database or file.
change line var bannerViews = 0; to something like;
var bannerViews = getValueFromServer();
and every after re assigning it, you store it back to the external storage;
For now everytime you refersh the page .
the code var bannerViews = 0; will run and hence bannerViews will alwayz be re assigned to 0
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!
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
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.