Function stops working after retrieving localStorage - javascript

I'm using localStorage on two lists, fruit-shelf & fruit-basket.
If you click on a fruit from fruit-shelf, it appends it to the fruit-basket, and if you refresh the page it's still there — so it remembers everything as it should.
Problem is: if you add one fruit, and then refresh page, you can't add more fruits, the program completely stops working.
I've added a Clear Local Storage button, which works. If you click on it and refresh page, you can add fruits again. But as soon as one fruit is added and you refresh page, you can't add more items to the fruit-basket.
I'm not sure how to put a name on the problem so it's hard to search for solutions (I've tried!).
Can someone point me in the right direction? :-)
Fiddle (I couldn't use SO Snippet here because of localStorage):
https://jsfiddle.net/nrv269hc/7/
JS:
(function() {
var btnClearStorage = document.querySelector('.btn-delete-all');
var fruitShelf = document.querySelector('.fruit-shelf');
var fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
var fruitBasket = document.querySelector('.fruit-basket');
// Store current state of fruitSheflf & fruitBasket
function storestate() {
localStorage.fruitShelf = fruitShelf.innerHTML;
localStorage.currentFruitBasket = fruitBasket.innerHTML;
};
function retrievestate() {
// Retrieve fruits left from shelf
if (localStorage.fruitShelf) {
fruitShelf.innerHTML = localStorage.fruitShelf;
}
// Retrieve stored fruits
if (localStorage.currentFruitBasket) {
fruitBasket.innerHTML = localStorage.currentFruitBasket;
}
};
retrievestate();
for (var i = 0; i < fruitShelfItems.length; i++) {
fruitShelfItems[i].addEventListener('click', function(event) {
fruitBasket.appendChild(this);
storestate();
});
}
// Clear Local Storage
btnClearStorage.addEventListener('click', function() {
localStorage.clear(fruitShelf);
localStorage.clear(fruitBasket);
});
})();

You need to update the fruitShelfItems as the HTML is update after retrievestate.
Look at updated JsFiddle
(function() {
var btnClearStorage = document.querySelector('.btn-delete-all');
var fruitShelf = document.querySelector('.fruit-shelf');
var fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
var fruitBasket = document.querySelector('.fruit-basket');
// Store current state of fruitSheflf & fruitBasket
function storestate() {
localStorage.fruitShelf = fruitShelf.innerHTML;
localStorage.currentFruitBasket = fruitBasket.innerHTML;
};
function retrievestate() {
// Retrieve fruits left from shelf
if (localStorage.fruitShelf) {
fruitShelf.innerHTML = localStorage.fruitShelf;
}
// Retrieve fruit basket
if (localStorage.currentFruitBasket) {
fruitBasket.innerHTML = localStorage.currentFruitBasket;
}
// you need to update the fruitShelfItems as the HTML is update after retrievestate
fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
};
retrievestate();
for (var i = 0; i < fruitShelfItems.length; i++) {
fruitShelfItems[i].addEventListener('click', function(event) {
fruitBasket.appendChild(this);
storestate();
});
}
// Clear Local Storage
btnClearStorage.addEventListener('click', function() {
localStorage.clear(fruitShelf);
localStorage.clear(fruitBasket);
});
})();

Related

How can I save a visual change a user made to my web page?

So I'm making a web page where users can press buttons to add elements using appendChild but when they refresh the page it all goes away. Is there something I can do to save what the users add to the page so that when they refresh it it stays the same?
HTML:
<input type="text" id="input" placeholder="write anything here...">
<button id="submit" onclick="createEl()">Submit</button>
<div class="text-div" id="text-div"></div>
CSS:
#input {
width: 500px;
height: 50px;
padding-left: 5px;
}
#submit {
height: 55px;
}
JAVASCRIPT:
var txtDiv = document.getElementById("text-div")
var inputField = document.getElementById("input")
function createEl() {
if (inputField.value !== "") {
var p = document.createElement("p")
var pNode = document.createTextNode(inputField.value)
p.appendChild(pNode)
txtDiv.appendChild(p)
}
}
In the absence of a database, you could try storing their progress within window.localStorage. On page load, you would need to run a function that checks for this item; if present, the function would then repopulate all of their information. After each submission, you would also need to update local storage so that their progress stays current.
Well, as people said earlier the if you want to load your data in all browsers regardless of where did those data came from, you should set up a database, based on your need and specification. Otherwise, you can get used to existing stuff in browsers such as localStorage. So you need to create a property in it, then on each page reload check whether there are data saved there or not with onload event.
So your final code should be something like this:
var txtDiv = document.getElementById("text-div")
var inputField = document.getElementById("input")
var items = [];
function createItem(item) {
var p = document.createElement("p")
var pNode = document.createTextNode(item)
p.appendChild(pNode)
txtDiv.appendChild(p)
}
window.onload = function() {
if (window.localStorage.getItem("items") !== null) {
items = JSON.parse(window.localStorage.getItem("items"))
var itemsLength = items.length
for (var i = 0; i < itemsLength; i++) {
createItem(items[i])
}
}
}
function createEl() {
if (inputField.value !== "") {
createItem(inputField.value)
items.push(inputField.value)
window.localStorage.setItem("items", JSON.stringify(items))
}
}
You will need to use some method of persistent storage. If you don't care about saving the changes forever, then you can save user changes in localStorage. If you need to make sure the changes will always be available, then you'll need to create a database and handle saving and loading data from an API that connects to it.
Here's an example of how to do this using localStorage:
var txtDiv = document.getElementById("text-div")
var inputField = document.getElementById("input")
const getSaved = () => JSON.parse(localStorage.getItem("saved"));
function saveEl(val) {
const saved = getSaved();
let newInputArr = saved ? [...saved, val] : [val];
localStorage.setItem("saved", JSON.stringify(newInputArr));
}
function createEl(val) {
var p = document.createElement("p")
var pNode = document.createTextNode(val)
p.appendChild(pNode)
txtDiv.appendChild(p)
}
function saveAndCreate() {
if((inputField.value !== "")) {
saveEl(inputField.value);
createEl(inputField.value);
}
}
const saved = getSaved();
if(saved && saved.length) {
saved.forEach((val) => {
createEl(val)
})
}

`How to change between list view and grid view and also keep the current state after page refresh

I need to toggle between list view and grid view which i was able to do using js to change the css but the problem is if a user refresh the page the default view is restored, how can I make this, probably append the view name to the url so that the current view will remain after user refresh page. example having the following URl www.example.com/item/search?q=myquery&style=list, www.example.com/item/search?q=myquery&style=grid, or is there a better way to do this. below is a fiddle of my code and any refresh will return the view to grid even when i select list view
JS FIDDLE
Note: I'm using yii2 framework so regarding the url formation i'm open to both php and JS solution, thanks in advance
$(".listView").on('click', function() {
listView();
});
$(".gridView").on('click', function() {
gridView();
});
// Get the elements with class="column"
var elements = document.getElementsByClassName("column");
// Declare a loop variable
var i;
// List View
function listView() {
for (i = 0; i < elements.length; i++) {
elements[i].style.width = "100%";
}
}
// Grid View
function gridView() {
for (i = 0; i < elements.length; i++) {
elements[i].style.width = "50%";
}
}
var container = document.getElementById("btnContainer");
var btns = container.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
In order to do what you want, actually you dun need to do any work on backend but simply using the cookie.
You may improve it, I just provide a picture.
$(".listView").on('click', function() {
listView();
setCookie('list');
});
$(".gridView").on('click', function() {
gridView();
setCookie('grid');
});
function setCookie(name) {
document.cookie = name;
}
And when you start the JS, check the cookie first by
var x = document.cookie;
if (x == 'list'){...}
else if (x == 'grid'){...}
You may also choose to use localStorage, the technical is the same. However, only when if you list and grid data has no difference, and no server data is further required.
I think MatrixTai has the right idea, but I personally prefer usually localStorage.
Here is an example with a functions for getting/setting the view:
$(".listView").on('click', function() {
listView();
setView('list');
});
$(".gridView").on('click', function() {
gridView();
setView('grid');
});
function setView(view) {
localStorage.setItem('view', view);
}
function getView(view) {
return localStorage.getItem('view');
}

How to keep input and page the same using local storage

Hi I wrote a code which has a working search with filters applied to it. The only problem I am having is that it doesn't stay the same as to how the filters where set when the user closes or refreshes the webpage. I am not using a checkbox
This is my code so far
saveTask: function(name, isCompleted) {
window.localStorage.setItem(name, isCompleted);
},
renderTasks: function() {
for (var i = 0; i < window.localStorage.length; i++) {
var taskName = window.localStorage.key(i);
var isCompleted = window.localStorage.getItem(taskName) == "true";
var taskHTML = Todo.template.replace("<!-- TASK_NAME -->", taskName);
if (!isCompleted) {
Todo.container.insertAdjacentHTML('afterbegin', taskHTML);
}
}
}
This is a js fiddle https://jsfiddle.net/4p8awnqx/6/
I am trying to keep the filters the same using local storage so that when it is closed or refreshed it stays the same

How to avoid a specific link in Tampermonkey

I've "created" a very small script for automatically clicking links on a specific site using TamperMonkey,
(function() {
'use strict';
var TargetLink = $("a:contains('Click Me')");
if (TargetLink.length)
window.location.href = TargetLink[0].href;
})();
When the link I'm trying to click, looks like this Click Me as an example.
What I'd like for the script to do, is avoid clicking on one specific "ID" and click all the other ones.
Example, I'd like to avoid clicking the ID 1, but click on 2, 3, and 4, where 4 are the amount of total ID's.
Not sure if I explained that as well as I would like to, but hopefully it's somewhat understandable.
You can use .filter() to remove the elements that you don't want.
In the filter I used split and slice to extract the id from href, then I check if the id is in idsBlacklist.
(function() {
'use strict';
var idsBlacklist = [
"1010101"
];
var query = "a:contains('Click Me')";
var TargetLink = $(query).filter(function () {
var id = this.href.split('/').slice(-1)[0];
return idsBlacklist.indexOf(id) < 0;
});
var blackListed = $(query).filter(function () {
var id = this.href.split('/').slice(-1)[0];
return idsBlacklist.indexOf(id) >= 0;
});
if (!blackListed.length && TargetLink.length) {
console.log(TargetLink[0].href);
//window.location.href = TargetLink[0].href;
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click Me
Click Me
Click Me

What event is triggered when a HTML5 Adobe Extension Panel is collapsed?

I am working on a HTML5 Adobe Extension that needs to load data from LocalStorage into some 's but for the life of me I can't figure out wether the panel is being collapsed or closed or what happens with it. The list items are generated dinamically.
I would also need an ideea to save data upon exit so that the list elements inside the UL can be saved and retrieved when PS starts again. So far I noticed that the host i a chrome type browser that supports a lot of stuff, including localstorage. However, I've not seen a dead simple tutorial for saving ul items but only for variables and strings.
right now I'm unable to save or retrieve the data from localstorage.
here is my code so far.
$(document).ready(function(){
var task = {
"name" : "",
"description" : "",
"project" : ""
};
$('#saveData').css("visibility", "hidden");
$('#btnMarkAsDone').css("visibility","hidden");
var toBeDone = Array();
var wasDone = Array();
$( window ).load(function() {
for(var i = 0;i < toBeDone.length;i++){
$('#todo').append('<li class="todo-item">'+toBeDone[i]+'</li>');
}
for(var i = 0; i < wasDone.length; i++){
$('#done').append('<li class="completed">'+wasDone[i]+'</li>');
}
});
$( window ).width(function() {
});
$("#btnAddTask").click(function(){
var oName = task.name;
var oProject = task.project;
var oDescription = task.description;
var taskname = $("#txtTaskName").val();
var taskproject = $("#txtTaskProj").val();
var taskdescription = $("#txtTaskDesc").val();
oName = taskname;
oProject = taskproject;
oDescription = taskdescription;
var input = "<b>Task: </b>"+oName+" | "+"<b>PSD: </b>"+oProject+" | "+"<b>Desc: </b>"+oDescription;
$("#todo").append('<li class="todo-item">'+input+'</li>');
});
$("#todo").on('click','li',function(){
$(this).addClass('complete');
$("#done").append(this);
});
$("#done").on('click','li',function(){
$(this).remove();
});
$("#saveData").click(function(){
if(localStorage['todo']){
toBeDone = JSON.parse(localStorage['todo']);
}if(localStorage['done']){
wasDone = JSON.parse(localStorage['done']);
}
});
$(function() {
$("button").button();
});
});
Fixed the localStorage part:
$("#saveData").click(function(){
var toDo = $('#todo').html();
var finished = $('#done').html();
localStorage.setItem('todo',toDo);
localStorage.setItem('done',finished);
});
$(window).load(function() {
$("#todo").html(localStorage.getItem('todo'));
$("#done").html(localStorage.getItem('done'));
});
Still need to find out what kind of event is fired when a window is collapsed though. I appreciate any help !

Categories

Resources