How to scroll forwards and backwards in a javascript array

Viewed 66

I am new to javascript and would really appreciate some help. The javascript below is connected to two buttons in an an html documented called "next" and "previous". The buttons are intended to allow a user to scroll forwards and backwards through an array that contains the letters of the alphabet. The code is almost working, but has one bug. Clicking the "next" button will display the next letter in alphabet (i.e. B will switch to C). However, clicking the "previous" button will display the next letter in the alphabet before changing directions. For example, if the letter "C" is displayed, clicking "previous" will display "D" and then "C", "B", "A", "Z", etc...

What changes need to be made to the code below to fix this problem? If a letter is displayed, I would like for the function "next" to return the next letter and for the function "previous" to return the letter that comes immediately before the letter being displayed.

function next(){
  let upperCase = ["A","B", "C", "D", "E","F", "G", "H", "I","J", "K", "L", "M","N", "O", "P", "Q","R", "S", "T", "U","V", "W", "X", "Y","Z"];
  
  document.querySelector(".item-2").innerHTML = upperCase[index++];

  if(index > upperCase.length - 1)
    index = 0;
}


function previous(){
  let upperCase = ["A","B", "C", "D", "E","F", "G", "H", "I","J", "Q", "L", "M","N", "O", "P", "Q","R", "S", "T", "U","F", "W", "X", "Y","Z"];
  
  document.querySelector(".item-2").innerHTML = upperCase[index--];

  if(index < 0)
    index = upperCase.length - 1;
}
1 Answers

You need to set ++ and -- before the index variable in order to return its value after incrementing it:

let index = 0;

const previousButton = document.getElementById('previous');
const nextButton = document.getElementById('next');

previousButton.addEventListener('click', previous);
nextButton.addEventListener('click', next);

const upperCase = ["A","B", "C", "D", "E","F", "G", "H", "I","J", "K", "L", "M","N", "O", "P", "Q","R", "S", "T", "U","V", "W", "X", "Y","Z"];

function next(){
  if(++index > upperCase.length - 1)
    index = 0;

  document.querySelector(".item-2").innerHTML = upperCase[index];
}


function previous(){
  if(--index < 0)
    index = upperCase.length - 1;

  document.querySelector(".item-2").innerHTML = upperCase[index];
}
<div class="item-2"></div>
<button id="previous">Previous</button>
<button id="next">Next</button>

Related