I use a filtering function in my webpage. When a button is clicked, it hides the associated elements and fades itself. Once it's clicked again, it brings those elements back and restores its color.
What I want to do is to add two additional buttons: "Show all" and "Hide all". I want them to show/hide all elements and also fade/restore all the button colors upon click.
First I made an onclick event handler for these two buttons, but it didn't work properly. I think I have to combine everything in the same onload event, and that's where I got stuck. Could you please help me to modify my js to achieve my goal?
Snippet:
for (let button of document.querySelectorAll(".filterbutton")) {
button.addEventListener("click", filter);
}
let filters = new Set;
function toggleDisplay(selector, display) {
let elems = document.querySelectorAll(selector);
for (let elem of elems) {
elem.style.display = display;
}
}
function filter() {
let filterSelector = this.dataset.filter;
let show = filters.delete(filterSelector);
this.style.color = show ? "" : "rgb(200,200,200)";
if (!show) {
filters.add(filterSelector); // toggle this filter
} else {
toggleDisplay(filterSelector, "");
}
if (filters.size) {
toggleDisplay([...filters].join(","), "none");
}
}
.filterbutton,
.showallbutton,
.hideallbutton {
border: 1px solid;
display: inline-block;
background: lightblue;
padding: 5px;
cursor: pointer
}
.group a {
display: block;
}
<div class="filter">
<div class="filterbutton" data-filter=".filter01">Filter 01</div>
<div class="filterbutton" data-filter=".filter02">Filter 02</div>
<div class="filterbutton" data-filter=".filter03">Filter 03</div>
</div>
<div class="group">
<a class="filter01 filter02 filter03">This element has filter01, filter02 and filter03</a>
<a class="filter01 filter02">This element has filter01 and filter02</a>
<a class="filter01 filter03">This element has filter01 and filter03</a>
<a class="filter02 filter03">This element has filter02 and filter03</a>
<a class="filter01">This element has filter01 only</a>
<a class="filter02">This element has filter02 only</a>
<a class="filter03">This element has filter03 only</a>
</div>
<div class="show-hide">
<div class="showallbutton">Show all</div>
<div class="hideallbutton">Hide all</div>
</div>