Reputation: 445
I try to boost my JavaScript knowledge. For this, I sometimes create some simple projects. As a reference, I use the only developer.mozilla resource and I recently tried to figure it out with localStorage. For this, I decided to create an elementary to-do list on pure JavaScrip. And I think, I figured out the principles of work localStorage. But I ran into other confusions.
When I add a new item to the list it's adding without any problem and displaying on the app interface. But when I try to mark it as done or delete it. Nothing comes. I just need to reload the page and then I can delete or mark the task completed without any problems.
HTML part
<div class="app-wrapper">
<section class="header">
<div class="header-inner">
<div class="app-title">ToDoList</div>
</div>
<form class="add-list-wrapper">
<input id="add-list__field" class="add-list__field" name="add-list__field" placeholder="" type="text">
<button type="button" id="add_list" class="add-list__btn">Add</button>
</form>
<div class="list-item__wrapper">
<div id="list-item__wrapper"></div>
</div>
<div class="clear-wrapper">
<button id="clear-list" class="clear-list" type="button">Clear All</button>
</div>
</section>
And here is the part of the JavaScript code responsible for adding the item to the list:
const chooseCathegory = document.getElementById('choose-cathegory');
const categoryWrapper = document.getElementById('category-wrapper');
const listCathegoryItem = document.querySelectorAll('.list__cathegory-item');
const addListBtn = document.getElementById('add_list');
const clearList = document.getElementById('clear-list');
const listArray = JSON.parse(localStorage.getItem('listArray')) || [];
function listCreator(){
let itemsArray = JSON.parse(localStorage.getItem('listArray'));
let listItemContent = "";
for (item in itemsArray) {
listItemContent +=
'<div class="list-item">'+
'<div data-item="'+item+'" title="Click for marking the task complete" class="list-item__content">'
+itemsArray[item]+
'</div>'+
'<div title="Remove this item" class="remover">'+
'<i class="far fa-trash-alt"></i>'+
'</div>'+
'</div>'+
'</div>';
}
document.getElementById("list-item__wrapper").innerHTML = listItemContent;
}
addListBtn.addEventListener('click', function(){
let addListFieldValue = document.getElementById('add-list__field').value;
const retrievedData = localStorage.getItem("favoriteItems");
let checkForMatches = JSON.parse(localStorage.getItem('listArray'));
if(checkForMatches !== null && checkForMatches.includes(addListFieldValue)){
alert("Come up with something original;")
}else{
listArray.push(addListFieldValue);
localStorage.setItem('listArray', JSON.stringify(listArray));
listCreator();
}
});
window.addEventListener('load', listCreator())
And this piece of code is responsible for deleting an element and marking it as done.
/*** Remove Item from List ***/
let removeItem = document.querySelectorAll('.remover');
removeItem.forEach(item=>{
item.addEventListener('click', function(){
this.closest('.list-item').style.display='none';
let dataItem = this.getAttribute('data-item');
let existingEntries = JSON.parse(localStorage.getItem('listArray'));
existingEntries.splice(dataItem, 1)
localStorage.setItem("listArray",JSON.stringify(existingEntries));
let completArray = JSON.parse(localStorage.getItem('completArray'));
completArray.splice(dataItem, 1)
localStorage.setItem("completArray",JSON.stringify(completArray));
});
});
/*** Mark as Complete ***/
let markComplet = document.querySelectorAll('.list-item__content');
const completArray = JSON.parse(localStorage.getItem('completArray')) || [];
markComplet.forEach(item=>{
item.addEventListener('click', function(){
let dataItem = this.getAttribute('data-item');
completArray.push(dataItem);
localStorage.setItem('completArray', JSON.stringify(completArray));
addCompletLine();
});
function addCompletLine(){
let dataItem = item.getAttribute('data-item');
if(completArray.includes(String(dataItem))){
item.classList.add('active')
}
}
window.addEventListener('load', addCompletLine())
});
I tried to swap functions. But all the same, the code works the same: I added an element, I try to delete it or mark it as executed, it doesn't work until you reload the page. I understand that somewhere there is a gross mistake, but I cannot find it because I do not have enough experience. Please help me to figure it out.
Upvotes: 0
Views: 74
Reputation: 2810
You are not adding the event listener when you add an item. Add an eventListener on load that handles all other necessary eventListeners.
I added a new function that handles your remove function.
This should work how you want it:
const chooseCathegory = document.getElementById('choose-cathegory');
const categoryWrapper = document.getElementById('category-wrapper');
const listCathegoryItem = document.querySelectorAll('.list__cathegory-item');
const addListBtn = document.getElementById('add_list');
const clearList = document.getElementById('clear-list');
const listArray = JSON.parse(localStorage.getItem('listArray')) || [];
function listCreator() {
let itemsArray = JSON.parse(localStorage.getItem('listArray'));
let listItemContent = "";
for (item in itemsArray) {
listItemContent +=
'<div class="list-item">' +
'<div data-item="' + item + '" title="Click for marking the task complete" class="list-item__content">' +
itemsArray[item] +
'</div>' +
'<div title="Remove this item" class="remover">' +
'<i class="far fa-trash-alt">Click to Remove</i>' +
'</div>' +
'</div>' +
'</div>';
}
document.getElementById("list-item__wrapper").innerHTML = listItemContent;
}
addListBtn.addEventListener('click', function() {
let addListFieldValue = document.getElementById('add-list__field').value;
const retrievedData = localStorage.getItem("favoriteItems");
let checkForMatches = JSON.parse(localStorage.getItem('listArray'));
if (checkForMatches !== null && checkForMatches.includes(addListFieldValue)) {
alert("Come up with something original;")
} else {
listArray.push(addListFieldValue);
localStorage.setItem('listArray', JSON.stringify(listArray));
listCreator();
removerClassListeners();
}
document.getElementById('add-list__field').value = "";
});
window.addEventListener('load', loadAll());
function removerClassListeners() {
console.log("called")
/*** Remove Item from List ***/
let removeItems = document.querySelectorAll('.remover');
removeItems.forEach(removeItem => {
removeItem.addEventListener('click', function() {
this.closest('.list-item').style.display = 'none';
let dataItem = this.getAttribute('data-item');
var existingEntries = JSON.parse(localStorage.getItem('listArray'));
existingEntries.splice(dataItem, 1)
localStorage.setItem("listArray", JSON.stringify(existingEntries));
var completArray = JSON.parse(localStorage.getItem('completArray'));
completArray.splice(dataItem, 1)
localStorage.setItem("completArray", JSON.stringify(completArray));
});
});
}
function loadAll() {
listCreator();
removerClassListeners();
}
/*** Mark as Complete ***/
let markComplet = document.querySelectorAll('.list-item__content');
const completArray = JSON.parse(localStorage.getItem('completArray')) || [];
markComplet.forEach(item => {
item.addEventListener('click', function() {
let dataItem = this.getAttribute('data-item');
completArray.push(dataItem);
localStorage.setItem('completArray', JSON.stringify(completArray));
addCompletLine();
});
function addCompletLine() {
let dataItem = item.getAttribute('data-item');
if (completArray.includes(String(dataItem))) {
item.classList.add('active')
}
}
window.addEventListener('load', addCompletLine())
});
<div class="app-wrapper">
<section class="header">
<div class="header-inner">
<div class="app-title">ToDoList</div>
</div>
<form class="add-list-wrapper">
<input id="add-list__field" class="add-list__field" name="add-list__field" placeholder="" type="text">
<button type="button" id="add_list" class="add-list__btn">Add</button>
</form>
<div class="list-item__wrapper">
<div id="list-item__wrapper"></div>
</div>
<div class="clear-wrapper">
<button id="clear-list" class="clear-list" type="button">Clear All</button>
</div>
</section>
</div>
Upvotes: 2
Reputation: 224
For it to work without reloading the page, you would need to add the click event listener after each list item is added.
Currently you're adding the event handler to all .remover elements when the page loads, but that wouldn’t* add the event listener to each element that is added after.
Upvotes: 1