El ciclo funciona solo una vez y luego no pasa nada. Tengo tres testimonios y solo puedo avanzar o retroceder una vez. ¡Gracias por la ayuda!
const nextBtn = document.querySelector(".next-btn"); const prevBtn = document.querySelector(".prev-btn"); const testimonials = document.querySelectorAll(".testimonial"); let index = 0; window.addEventListener("DOMContentLoaded", function () { show(index); }); function show(index) { testimonials.forEach((testimonial) => { testimonial.style.display = "none"; }); testimonials[index].style.display = "flex"; } nextBtn.addEventListener("click", function () { index++; if (index > testimonials.length - 1) { index = 0; } show(index); }); prevBtn.addEventListener("click", function () { index--; if (index < 0) { index = testimonials.length - 1; } show(index); });Usaría una clase "oculta" para ocultar los testimonios no activos en lugar de manipular el estilo del elemento en línea. Además, su lógica de navegación se puede simplificar a una operación de módulo.
El código que publicó originalmente pareció funcionar bien, pero parece estar repleto de redundancia (reutilización de código). También carece de flujo estructural (legibilidad).
const modulo = (n, m) => (m + n) % m, moduloWithOffset = (n, m, o) => modulo(n + o, m); const nextBtn = document.querySelector('.next-btn'), prevBtn = document.querySelector('.prev-btn'), testimonials = document.querySelectorAll('.testimonial'); let index = 0; const show = (index) => { testimonials.forEach((testimonial, currIndex) => { testimonial.classList.toggle('hidden', currIndex !== index) }); } const navigate = (amount) => { index = moduloWithOffset(index, testimonials.length, amount); show(index); } // Create handlers const onLoad = (e) => show(index); const onPrevClick = (e) => navigate(-1); const onNextClick = (e) => navigate(1); // Add handlers window.addEventListener('DOMContentLoaded', onLoad); nextBtn.addEventListener('click', onNextClick); prevBtn.addEventListener('click', onPrevClick); .testimonial { display: flex; } .testimonial.hidden { display: none; } <div> <button class="prev-btn">Prev</button> <button class="next-btn">Next</button> </div> <div> <div class="testimonial">A</div> <div class="testimonial">B</div> <div class="testimonial">C</div> <div class="testimonial">D</div> <div class="testimonial">E</div> <div class="testimonial">F</div> </div>