So when bin icon is clicked, the URL next to it will be removed. My HTML code is below:
<div class="container">
<input type="text" id="input" placeholder="Type..">
<div class="button-container">
<button id="save-input">SAVE INPUT</button>
</div>
<ul id="view">
</ul>
</div>
My JS code is below:
let list = [];
const input = document.getElementById('input');
const saveInput = document.getElementById('save-input');
const view = document.getElementById('view');
const localList = JSON.parse( localStorage.getItem("list") )
if (localList) {
list = localList;
render(list);
}
saveInput.addEventListener('click', function (){
if(input.value){
list.push(input.value);
input.value = '';
localStorage.setItem('list', JSON.stringify(list));
render(list); }
})
let remove = document.querySelectorAll(".remove");
Array.from(remove).forEach((el) => {
el.addEventListener('click', function() {
let index = el.getAttribute('data-index');
list.splice(index, 1);
localStorage.setItem('list', JSON.stringify(list));
render(list);
})});
function render(lst) {
let listItems = '';
lst.forEach((element, index) => {
listItems = `
<li>
<a href='${element}'>${element}</a>
<img src="images/remove.png" class="remove" data-index="${index}">
</li>`
});
view.innerHTML = listItems;
}
The problem with that code is that it is only working when page is refreshed before each removing. How can I solve this?
CodePudding user response:
Delegate a click
event listener which deletes the entry (by using Element.closest()
to get the first parent li
element) and removes it from localStorage
:
document.addEventListener('click', function(e) {
if (e.target.classList.contains('remove')) {
e.target.closest('li').remove()
let index = e.target.getAttribute('data-index');
list.splice(index, 1);
localStorage.setItem('list', JSON.stringify(list));
}
})
Jsfiddle demo: https://jsfiddle.net/Spectric/j4dc63ro/