everyone. I am new to the programming and I can't figure out how to refactor this code using loops, so the panels would be switching exactly like in the slider by pressing right arrow key(I commented out my attempt).
document.addEventListener("keydown", (e) => {
if (e.key === "ArrowRight") {
if (panels[0].classList.contains("active")) {
panels[0].classList.remove("active");
panels[1].classList.add("active");
} else if (panels[1].classList.contains("active")) {
panels[1].classList.remove("active");
panels[2].classList.add("active");
} else if (panels[2].classList.contains("active")) {
panels[2].classList.remove("active");
panels[3].classList.add("active");
} else if (panels[3].classList.contains("active")) {
panels[3].classList.remove("active");
panels[4].classList.add("active");
} else if (panels[4].classList.contains("active")) {
panels[4].classList.remove("active");
panels[0].classList.add("active");
}
// for (let i = 0; i < panels.length; i ) {
// if (panels[i].classList.contains("active")) {
// panels[i].classList.remove("active");
// panels[ i].classList.add("active");
// }
// if (i > panels.length - 1) {
// panels[panels.length - 1].classList.remove("active");
// panels[0].classList.add("active");
// }
// }
// }
}
});
CodePudding user response:
you can do something like this :
document.addEventListener("keydown", (e) => {
if (e.key === "ArrowRight") {
for(let i=0; i< 5; i ) {
let j = (i 1)%5;
if (panels[i].classList.contains("active")) {
panels[i].classList.remove("active");
panels[j].classList.add("active");
break;
}
}
}
});
This code uses modulo, so that in the last loop, the second number eqauls to
5%5 = 0