I am working on a to-do list project. The problem is if someone wants to filter the list by clicking on the buttons active, completed and all applications will not work until you click on the refresh button in the browser before that. In this app, I'm also using localStorage. Can someone check the code and tell me why is this happening, please?
'use strict';
const tabInput = document.querySelector('.tab-input');
const input = document.getElementById('input');
const todosUl = document.querySelector('.todos');
const clearBtn = document.querySelector('.span-right');
const counterItem = document.querySelector('.number');
const body = document.getElementById('body');
const light = document.querySelector('.light');
const icon = document.querySelector('.todo-icon');
// filter 1
const buttons = document.querySelector('.btn-grup');
const filters = document.querySelectorAll('.button--filter');
function btnClicked() {
buttons.addEventListener('click', (e) => {
const clicked = e.target;
if (!clicked) return;
filters.forEach((filter) => filter.classList.remove('active'));
clicked.classList.add('active');
});
}
// filter
let todosEl = document.querySelectorAll('li');
// completed
function filterCompleted() {
todosEl.forEach((el) => {
if (!el.classList.contains('completed')) {
el.style.display = 'none';
} else {
el.style.display = 'block';
}
});
}
// active
function filterActive() {
todosEl.forEach((el) => {
if (el.classList.contains('completed')) {
el.style.display = 'none';
} else {
el.style.display = 'block';
}
});
}
// all
function filterAll() {
let todosEl = document.querySelectorAll('li');
todosEl.forEach((el) => {
if (el || el.classList.contains('completed')) {
el.style.display = 'block';
}
});
}
// btn clear
clearBtn.addEventListener('click', (e) => {
localStorage.clear();
location.reload();
});
HTML
<form class="tab-input" id="tab-input">
<input
type="text"
class="input"
id="input"
placeholder="Create a new todo..."
autocomplete="off"
/>
<ul class="todos" id="todos"></ul>
<div class="item-info">
<span class="span-left"
><span class="number"></span> items left</span
>
<span class="span-right">Clear</span>
</div>
<div class="btn-grup">
<button
class="button--filter active"
onclick="filterAll(); btnClicked()"
id="filter-all"
type="button"
>
All
</button>
<button
class="button--filter"
onclick="filterActive(); btnClicked()"
id="filter-active"
type="button"
>
Active
</button>
<button
class="button--filter"
onclick="filterCompleted(); btnClicked()"
id="filter-completed"
type="button"
>
Completed
</button>
</div>
</form>