I'm working on a simple to-do list with vanilla js. I've managed to add the input to local storage, but have not been able to add the style changes(check strike through) to local storage, nor can I figure out how to remove one item at a time from storage. I have been able to clear all, just unable to remove each item separately. Below is my code, any advice is greatly appreciated.
//local storage setup
let saved = window.localStorage.getItem(input.value);
if (saved) {
list.innerHTML = saved;
}
//handle input submit
function handleSubmitForm(e) {
e.preventDefault();
let input = document.querySelector('input');
if (input.value != '') {
addTodo(input.value);
}
input.value = '';
window.localStorage.setItem(input.value, list.innerHTML);
}
//check off todo
function checkTodo(e) {
let item = e.target.parentNode;
if (item.style.textDecoration == 'line-through') {
item.style.textDecoration = 'none';
} else {
item.style.textDecoration = 'line-through';
}
window.localStorage.setItem(item);
}
//delete todo
function deleteTodo(e) {
let item = e.target.parentNode;
item.addEventListener('transitionend', function () {
item.remove();
});
item.classList.add('todo-list-item-fall');
window.localStorage.removeItem(item);
}
JavaScript Storage is a key-value pair. Just use a string-based key so you can remove, edit or read it easily.
// Set todo item
localStorage.setItem("todo1", "Stand-up meeting 9.15am");
// Read todo item
localStorage.getItem("todo1");
// Delete todo item
localStorage.removeItem("todo1");
It's better if you can save it as a JSON string because you can mark it as completed without delete, so you can find completed tasks too.
// Saving todo item as a JSON string
localStorage.setItem("todo1", JSON.stringify({ text: "Stand-up meeting 9.15am", completed: false }));
// Read it
const todo = JSON.parse(localStorage.getItem("todo1"));
// You can read the text
console.log(todo.text);
// Also you can mark it as completed and save it back
todo.completed = true;
localStorage.setItem("todo1", JSON.stringify(todo));
Storing object in localStorage is a tricky job.
Everything you store in the local or session storage is of type string
you can create an object like
item = {
value : ANY_VALUE
}
and save it in your localStorage using JSON.stringify
localStorage.setItem(`item`,JSON.stringify(item))
now when you want to update the item just update the object and again set using the ablove syntax
To access the saved item from the local storage use JSON.parse
yourItemObject = JSON.parse(localStorage.getItem())```
You can access values now using yourItemObject .value
It appears you're passing the whole HTML element (it passed as an object) inside the removeItem function. you need to pass the key instead.
try localStorage.removeItem(item.innerText);
If you are working with lists in localStorage. I would use something like this basic example:
function addTodo(key, item){
var list = getTodo(key);
list.push(item);
localStorage.setItem(key, JSON.stringify(list) );
}
function getTodo(key){
try{
var rawList = localStorage.getItem(key);
return JSON.parse(rawList) || [];
}
catch(e){
return [];
}
}
function removeTodo(key, id){
var list = getTodo(key);
var newlist = list.filter( function(item){
return item.id != id;
});
localStorage.setItem(key, JSON.stringify(newlist) )
}
function emptyTodo(key){
localStorage.removeItem(key);
}
addTodo('list', {
id: 1,
text: 'do shopping'
});
addTodo('list', {
id: 2,
text: 'study'
});
console.log( getTodo('list') );
removeTodo('list', 1);
console.log( getTodo('list') )
emptyTodo('list');
I am using Ionic and I am saving the preference of a user in localstorage.
Now, I would want to show this data in the profile of this person (so in a different screen / page), yet I have no clue how I should fetch this data.
Could someone help me out?
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
// add class 'fav' to each favorite
favorites.forEach(function(favorite) {
document.getElementById(favorite).className = 'fav';
});
// register click event listener
document.querySelector('.list').addEventListener('click', function(e) {
var id = e.target.id,
item = e.target,
index = favorites.indexOf(id);
// return if target doesn't have an id (shouldn't happen)
if (!id) return;
// item is not favorite
if (index == -1) {
favorites.push(id);
item.className = 'fav';
// item is already favorite
} else {
favorites.splice(index, 1);
item.className = '';
}
// store array in local storage
localStorage.setItem('favorites', JSON.stringify(favorites));
});
// local storage stores strings so we use JSON to stringify for storage and parse to get out of storage
This is my Codepen:
https://codepen.io/CrocoDillon/pen/pIlKB
As long as you are staying on the same domain, you should have access to the same localStorage object. So this should work:
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
const favorites = JSON.parse(localStorage.getItem('favorites')) || [];
localStorage.getItem('favorites') itself is an accessor
I am creating a song book app with 'add to favorite' button. i have song1.html song2.html and favorite.html.
in song1.html, when add to favorite button is clicked. i am storing the link to that song in local storage.
This is my song1.html
<!DOCTYPE html>
<html>
<body>
<button onclick="mySongOne()">add to favorite</button>
<script>
function mySongOne() {
localStorage.setItem("favsong", "<a href='https://www.song1.com'><h1>song1</h1></a>");
}
</script>
</body>
</html>
in song2.html, when add to favorite button is clicked. i am storing the link of the second song in local storage.
song2.html
<!DOCTYPE html>
<html>
<body>
<button onclick="mySongTwo()">add to favorite</button>
<script>
function mySongTwo() {
localStorage.setItem("favsong", "<a href='https://song2.com'><h1>song2</h1></a>");
}
</script>
</body>
</html>
now i have a favorite.html for listing my favourite songs. and favourite.html will retrieve the links that i stored in local storage.
favorite.html
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<div id="result"></div>
<script>
function myFunction() {
document.getElementById("result").innerHTML = localStorage.getItem("favsong");
}
</script>
</body>
</html>
Now i want to show both song 1 and song 2 in favorite.html.
but only song 2 is displayed in favourite.html. How to accomplish this.
Store list in javascript Array.
You need to either use different keys or store multiple strings in array and then JSON.stringify that to save in localStorage.
Similary when you get the same string from localStorage then convert it into object using JSON.parse.
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
let list = [];
list.push("<h1>John<h1>");
list.push("<h2>David<h2>");
localStorage.setItem("list", JSON.stringify(list));
// Retrieve
document.getElementById("result").innerHTML = JSON.parse(localStorage.getItem("list"));
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
</body>
</html>
When using localStorage, you can only have one item per key. localStorage allows you to store string-data as the value, thus we can use JSON.
You can serialize an array of items you want to add and then append them to the key inside of localStorage.
References:
JSON.stringify()
JSON.parse()
localStorage
JSFiddle. StackOverflow doesn't allow localStorage so I hosted my code there.
Code:
let items = ['<h1>John<h1>', '<h2>David<h2>', '<h3>Mary<h3>', '<h4>Bob<h4>'];
// Stringify the array and store it
localStorage.setItem("list", JSON.stringify(items));
// Parse the stringified array back from localStorage
let itemsRetrieved = JSON.parse(localStorage.getItem('list'));
// Get div with .list class
let div = document.querySelector('.list');
// Iterate retrieved array and append items
itemsRetrieved.forEach(item => {
div.innerHTML += item;
});
// Add an item
itemsRetrieved.push('<span style="color: red;">Dylan</span>');
// Stringify the new array and overwrite the key
localStorage.setItem("list", JSON.stringify(itemsRetrieved));
Code [For those who love encapsulation]:
let items = ['<h1>John<h1>', '<h2>David<h2>', '<h3>Mary<h3>', '<h4>Bob<h4>'];
// Stringify the array and store it [Initial]
localStorage.setItem("list", JSON.stringify(items));
// Returns parsed array
function getData(key) {
return JSON.parse(localStorage.getItem(key));
}
// Returns new array
function addData(key, item) {
// Get current array
let currentData = getData(key);
// Add an item
currentData.push(item);
// Stringify the new array and overwrite the key
localStorage.setItem(key, JSON.stringify(currentData));
return currentData;
}
// Parse the stringified array back from localStorage
let itemsRetrieved = getData('list');
// Get div with .list class
let div = document.querySelector('.list');
// Add an item
itemsRetrieved = addData('list', '<span style="color: red;">Dylan</span>');
// Iterate retrieved array and append items
itemsRetrieved.forEach(item => {
div.innerHTML += item;
});
If you really need to append data to the same LocalStorage key, there is no built-in append function.
However, you can use a custom function, for instance the one proposed in this answer: https://stackoverflow.com/a/7680123/2446264, and get the following code to do what you want:
<!DOCTYPE html>
<html>
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("list", "<h1>John<h1>");
appendToStorage("list", "<h2>David<h2>");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("list");
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
function appendToStorage(name, data){
var old = localStorage.getItem(name);
if(old === null) old = "";
localStorage.setItem(name, old + data);
}
</script>
</body>
</html>
Basically, you'll need to store those data as a list of strings (or use different keys 'list1', 'list2' etc...).
So, when you are putting your value into the local storage initially, you'll need to do something like this:
var initialValue = ['<h1>John<h1>']; // array of strings
// since Local Storage accepts only string values,
// you can store an array or any other object by using JSON.stringify function
localStorage.setItem('list', JSON.stringify(initialValue);
// updating local storage
var list = JSON.parse(localStorage.getItem('list');
list.push('<h2>David<h2>');
localStorage.setItem('list', JSON.stringify(list));
Then you can append those value by looping through the list.
var output = '';
for (var i = 0; i < list.length; i++) {
output = output + list[i];
}
document.getElementById("result").innerHTML = output;
What you are doing wrong:
localstorage doesn't store data types, but rather stores a string.
For instance, if you was to store an integer in a localstorage property, the data type would always be returned as a string.
Since you are attempting to store an array of values, you will need to create a CSV (comma-separated values) method.
var strLocalStorage = "John, Peter, Fred, Paul, Mary, Elizabeth";
You can the parse this into local storage using one of two methods
JSON (See example beneath)
SPLIT (variable.split(", ");
It is important you should be aware, Browsers set limitations of 5MB of data allocated between LocalStorage and SessionStorage.
This can cause problems when a large amount of data needs to be stored, in the event of your edited example, storing various URLs
What may be an alternative to your solution, would be to create CSV of favourite songs using your SQL Table's unique ID for the song table entry.
However, in the event your code is only using Front End languages such as HTML and JAVASCRIPT, then you may prefer to use IndexedDB
How to use Indexed DBs
This will allow you to create a local database that is accessible offline and allows you to recall and edit the values easier such as
LocalStorage Example:
var blLocalStorage = false;
function funInitiate(){
if (typeof(Storage) !== "undefined") {
console.log("localstorage detected on this browser");
blLocalStorage = true;
}else{
console.log("local storage is not supported by this browser, please update");
}
}
function funTestLocalStorage(){
var strLocalStorage = localStorage.getItem("FavSongs");
if(strLocalStorage === null){
return false;
}else{
return true;
}
}
function funGetSongFavorites(){
if(blLocalStorage){
if (funTestLocalStorage()){
var arrLocalStorage = JSON.parse(localStorage.getItem("FavSongs"));
var elOutput = document.querySelector("#result");
for(i = 0; i < arrLocalStorage.length; i++){
elOutput.innerHTML += "<br>" + arrLocalStorage[i]
}
}
}else{
console.log("No local storage - function funGetSongFavourites aborted");
}
}
function funAddFav(strURL){
if(blLocalStorage){
var strLocalStorage = localStorage.getItem(strURL);
if(strLocalStorage === null){
localStorage.setItem("FavSongs", strURL);
}else{
var arrList = JSON.parse(localStorage.getItem('FavSongs'));
arrList.push(strURL);
}
localStorage.setItem('FavSong', JSON.stringify(arrList));
console.log("Favourite Lists update: " + strURL);
}else{
console.log("No local storage - Function funAddFav aborted");
}
}
document.addEventListener("DOMContentLoaded", funInitiate, false);
<!DOCTYPE html>
<html>
<head>
<title>Webpage Title</title>
<script src="pathToJSScriptShownBeneath"></script>
</head>
<body>
<button onclick="funAddFav('http://youtube.com')">
Add to favorite
</button>
<div id="result"></div>
</body>
</html>
Indexed DB example
var songList = [
{ id: 1, artist: "2pac", title: "Dear Mama", URL: "https://www.youtube.com/watch?v=Mb1ZvUDvLDY" },
{ id: 2, artist: "Biggie Smalls", title: "Hypnotize", URL: "https://www.youtube.com/watch?v=glEiPXAYE-U" }
];
const dbName = "favSongs";
var request = indexedDB.open(dbName, songList.length);
request.onerror = function(event) {
console.log("An Error has occured, script will now exist";
return;
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("SongList", { keyPath: "id" });
// There can be multiple songs by 1 artist or band therefore this will
// declare this as a false unique entry, the sample applies for song titles
// some songs have the same title but performed by different artists.
objectStore.createIndex("artist", "artist", { unique: false });
objectStore.createIndex("title", "title", { unique: false });
// Song URLs will be unique, so we set this as a individually unique
objectStore.createIndex("URL", "URL", { unique: true });
// Use transaction oncomplete to make sure the objectStore creation is
// finished before adding data into it.
objectStore.transaction.oncomplete = function(event) {
// Store values in the newly created objectStore.
var customerObjectStore = db.transaction("favSongs", "readwrite").objectStore("SongList");
customerData.forEach(function(songList) {
customerObjectStore.add(songList);
});
};
};
// Retrieving Data:
var transaction = db.transaction(["favSongs"]);
var objectStore = transaction.objectStore("SongList");
var request = objectStore.get(2);
request.onerror = function(event) {
console.log("Entry doesnt exist of has been deleted");
};
request.onsuccess = function(event) {
var strArtist = request.result.artist;
var strTitle = request.result.title;
var strURL = request.result.URL;
};
// Deleting Data
var request = db.transaction(["favSongs"], "readwrite")
.objectStore("SongList")
.delete(1);
request.onsuccess = function(event) {
console.log ("Entry 1 has been deleted");
};
Add item: localStorage.name = 'Name'
Get item: let name = localStorage.name
Remove item: localStorage.removeItem('name')
I'm new to Firebase functions and trying to understand how to get a certain key from the database .onCreate trigger. Here is an example:
exports.createUserRoundData =
functions.database.ref('/data/players/{user_key}/').onCreate(event => {
var eventData = event.data.val();
var userKey = event.params.user_key;
var itemKey = eventData.items; // This returns an object
});
The structure is:
players > user_key > items > item_key > data
In the above scenario how can I retrieve the item_key?
Yes you can,
You need something like this :
exports.createUserRoundData = functions.database.ref('/data/players/{user_key}/').onCreate(event => {
var userKey = event.params.user_key; // Get user key parameter
var eventSnapshot = event.data; // Get player data
var itemsSnapshot = eventSnapshot.child('items'); // Get items data
itemsSnapshot.forEach(function(itemSnapshot) { // For each item
var itemKey = itemSnapshot.key; // Get item key
var itemData = itemSnapshot.val(); // Get item data
});
});
Here the Firebase Cloud Functions documentation.
I have a bug in my code that only saves the last object in an array upon reload. I have a feeling that my addAccount() function is not saving or inserting data correctly. Everything else works correctly. In my console, it shows that the data is being inserted into the array, but when I refresh I only get the last object saved.
I'm not sure what to do.
// The list of accounts array.
var accountsArray = [];
function addAccount() {
// Take fields and put user data into varables.
var accountName = document.getElementById('accountName').value;
var accountBalance = document.getElementById('accountBalance').value;
var accountType = document.getElementById("accountType");
var accountTypeSelected = accountType.options[accountType.selectedIndex].text;
var accountCurrency = document.getElementById("accountCurrency");
var accountCurrencySelected = accountCurrency.options[accountCurrency.selectedIndex].text;
var temporaryObject = {
'accountName': accountName,
'accountBalance': accountBalance,
'accountTypeSelected': accountTypeSelected,
'accountCurrencySelected': accountCurrencySelected
};
accountsArray.push(temporaryObject);
console.log(accountsArray);
saveAccountData();
showAccountsArray();
}
function saveAccountData() {
localStorage.setItem('accountsArray', JSON.stringify(accountsArray));
}
function showAccountsArray() {
//var accountsLocalStorage = JSON.parse(localStorage['accountsArray']);
if (localStorage.getItem("accountsArray") === null) {
document.getElementById("getStarted").style.visibility="visible";
document.getElementById("balanceToolbarName").style.visibility="hidden";
document.getElementById("accountsMainList").style.visibility="hidden";
} else {
var accountsLocalStorage = JSON.parse(localStorage['accountsArray']);
console.log(accountsLocalStorage);
var accountInfo = '';
var i = 0;
while (i < accountsLocalStorage.length) {
accountInfo += '<li class="swipeout"><div class="swipeout-content item-content"><div class="item-inner"><div class="item-title">' + accountsLocalStorage[i].accountName + '</div><div class="item-after">$' + accountsLocalStorage[i].accountBalance + '</div></div></div><div class="swipeout-actions-left"><a href="#" class="action1">Clear</div><div class="swipeout-actions-right">Delete</div></a></li>';
document.getElementById("accountsList").innerHTML = accountInfo;
i++;
}
document.getElementById("getStarted").style.visibility="hidden";
document.getElementById("balanceToolbarName").style.visibility="visible";
document.getElementById("accountsMainList").style.visibility="visible";
}
}
*
all of your functions work correctly as tested by the link you've provided. When the page loads it successfully retrieves the data (if any) from the local storage and displays on the page. However, the global array variable accountsArray is populated with data retrieved from the local storage.
You need to repopulate the global array otherwise when you call saveAccountData it will save whatever the array holds which indeed overrides whatever you had in the local storage. To fix it, simply add add this code block...
$(function(){
var data = localStorage.getItem("accountsArray");
if(data != null)
accountsArray = JSON.parse(localStorage.getItem("accountsArray"));
});