Search code examples
javascriptjqueryarraysincrementkeypress

How to get an array to increment with keypress


I need to increment my array with a keypress. I can get the first element of the array to display but can't get the other elements of the array to display when i press another key.

I've used an alert to get a message to display with a keypress and can get the first element in the array to display but can't get the other elements of the array to display when I press the key again.

function display_phrase() {
  var arrayPhrase = ['Relax!', 'Dont Do It!', 'Chill!', 'Take It Easy!', 'Do It!', 'Panic!', 'Beat It!','Forget About It!','Wooooo!','Oh Bother!'];   
  var arrayCounter = 0;
  var arrayPosition = (arrayCounter % arrayPhrase.length);

  $("#display_phrase").html("<h1>" +arrayPhrase[arrayPosition] +".</h1>");
}

var arrayCounter = 0;

$(document).ready(function() {
  $('body').keypress(function() {
    display_phrase();
    arrayCounter++;
  });
});

Solution

  • In your version, display_phrase masks the global arrayCounter variable with a local variable of the same name. To fix it, remove the local var arrayCounter = ... and keep the declaration in a higher scope.

    For example:

    var arrayPhrase = ['Relax!', 'Dont Do It!', 'Chill!', 'Take It Easy!', 'Do It!', 'Panic!', 'Beat It!','Forget About It!','Wooooo!','Oh Bother!'];   
    var arrayCounter = 0;
    
    function display_phrase() {
        var arrayPosition = (arrayCounter % arrayPhrase.length);
    
        $("#display_phrase").html("<h1>" +arrayPhrase[arrayPosition] +".</h1>");
    }
    
    ...