user2829045
user2829045

Reputation:

Rotating Messages with Keypress - Jquery

I am trying to rotate an array, anytime an alphanumeric key is pressed, a message displays. Below is the code I started working. I am trying to make the loop work, but it isn't working. Any feedback is appreciated.

var rotatingMessages = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];

$(document).ready(function() { 
$(document).keypress(function(e){
var code = e.KeyCode || e.which;
var messages = (code-1) % 10;

 $("div#output").html(rotatingMessages[messages]);
  });
});

Upvotes: 1

Views: 926

Answers (1)

PSL
PSL

Reputation: 123739

You can do it using shift and push to enable the cycling of array values.

var rotatingMessages = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
$(document).ready(function () {
    $(document).keypress(function (e) {
        var msg = rotatingMessages.shift(); //get the top value from the array
        rotatingMessages.push(msg); //push it to the end for cycle to repeat
        $("#output").html(msg);
    });
});

Fiddle

Upvotes: 1

Related Questions