How would I go about calling a function multiple times in different parts of my code. Currently I am just replicating the function and giving all of the variables a different name and calling that separate variable. I will add an example below. The method works but there is no way its efficient. What would be the better way to do it? Thank you for the help and I apologize for the silly question.
JS
// Variable 1
const filterButtons = document.querySelector("#filter-btns").children;
const items = document.querySelector(".blog__content").children;
for(let i =0; i < filterButtons.length; i ) {
filterButtons[i].addEventListener("click", function(){
for (let j =0; j < filterButtons.length; j ) {
filterButtons[j].classList.remove("active2")
}
this.classList.add("active2");
const target = this.getAttribute("data-target")
for (let k = 0; k < items.length; k ) {
items[k].style.display = "none";
if (target == items[k].getAttribute("data-id")) {
items[k].style.display = "block";
}
if (target == "all") {
items[k].style.display = "block";
}
}
})
}
// Variable 2
const filterButtons2 = document.querySelector("#filter-btns2").children;
const items2 = document.querySelector(".blog__content").children;
for(let i =0; i < filterButtons2.length; i ) {
filterButtons2[i].addEventListener("click", function(){
for (let j =0; j < filterButtons2.length; j ) {
filterButtons2[j].classList.remove("active2")
}
this.classList.add("active2");
const target = this.getAttribute("data-target")
for (let k = 0; k < items2.length; k ) {
items2[k].style.display = "none";
if (target == items2[k].getAttribute("data-id")) {
items2[k].style.display = "block";
}
if (target == "all") {
items2[k].style.display = "block";
}
}
})
}
HTML
<div id="filter-btns">
<a data-target="corn">
<span>Corn</span>
</a>
</div>
<div id="filter-btns2">
<a data-target="chicken">
<span>Chicken</span>
</a>
</div>
CodePudding user response:
First, you need a function to call if you want to call it twice
function fn(query) {
const filterButtons = document.querySelector(query).children;
const items = document.querySelector(".blog__content").children;
for (let i = 0; i < filterButtons.length; i ) {
filterButtons[i].addEventListener("click", function () {
for (let j = 0; j < filterButtons.length; j ) {
filterButtons[j].classList.remove("active2");
}
this.classList.add("active2");
const target = this.getAttribute("data-target");
for (let k = 0; k < items.length; k ) {
items[k].style.display = "none";
if (target == items[k].getAttribute("data-id")) {
items[k].style.display = "block";
}
if (target == "all") {
items[k].style.display = "block";
}
}
});
}
}
Then you can call it twice
fn('#filter-btns');
fn('#filter-btns2');