I have an index of projects that I want to be able to filter on click. The filter itself works fine on every click with the following code by hiding the visibility of non-highlighted projects, but the innerHTML of the filter ("all works" versus "selected works") only updates when there’s an odd number of total projects in the index.
highlighter.innerHTML = "selected works";
highlighter.addEventListener("click", function reels(e) {
const indexer = document.querySelectorAll(".index").length;
console.log(indexer);
//innerHTML updates when there are 3/5/7 index divs
//innerHTML does NOT update when there are 4/6/8 index divs
if (
highlighter.innerHTML.includes("all works") === false &&
highlight === "no"
) {
index.classList.toggle("visibility");
highlighter.innerHTML = "all works";
// console.log("selected are showing");
} else if (
highlighter.innerHTML.includes("all works") === true &&
highlight === "no"
) {
highlighter.innerHTML = "selected works";
index.classList.toggle("visibility");
// console.log("all are showing");
} else {
null;
}
});
I’ve tried moving the initial highlighter.innerHTML = "selected works"; into the if statement, but then there’s no text on the filter button when the page loads, and I want to avoid hard coding it into the html. Working in pure vanilla javascript is mandatory for this project.
2
Answers
Instead of using innerHTML try to use a variable to track if all projects are showing
Without the HTM we can only guess about your actual intentions. But even so it seems obvious that your code can be shortened and freed from quite a few redundancies. The following is my take on toggling between the display states of "all works" and "selected works":
I have as yet no idea what the variable
highlight
is supposed to do but I kept it in the code with the value"no"
nonetheless.