forward and reverse loop one by one js code example
Example: forward and reverse loop one by one js
var arr = ['red', 'blue', 'black', 'green'];
var currentIndex = 0;
var nextBtn = document.getElementById('nextBtn');
var prevBtn = document.getElementById('prevBtn');
nextBtn.addEventListener('click', nextItem);
prevBtn.addEventListener('click', prevItem);
function nextItem() {
if (currentIndex === (arr.length - 1)) {
return;
}
console.log(
arr[++currentIndex]
);
}
function prevItem() {
if (currentIndex === 0) {
return;
}
console.log(
arr[--currentIndex]
);
}