Nocturne
Nocturne

Reputation: 13

Navigate slideshow with right/left arrow keys using jQuery

This is kind of a slideshow that I made with jQuery. How can I use left and right keys on the keyboard to do the same thing as I am doing with the click event?

var x = 0;
$("#right-arrow").click(function(){
  if (x<3){
    x = x + 1;
    $("#wrapper").animate({ top: '-=400px' }, 1000);
  };
});
$("#left-arrow").click(function(){
  if (x>0){
    x = x - 1;
    $("#wrapper").animate({ top: '+=400px' }, 1000);
  };
});

Upvotes: 0

Views: 590

Answers (2)

Beingnin
Beingnin

Reputation: 2422

Keyboard entries are normally bound with the following events: keydown, keyup and keypress. You can use any of them and check which key is pressed by checking it's code property. You should not use the keyCode property as it is deprecated.

Edit: From the comments it is understood that the keypress event is deprecated. So avoid using it anymore.

JavaScript key codes here

$(document).keydown(function(e) {
  if (e.code == 37)//left arrow
  {
   //your logic for left arrow press
  }
  if (e.code == 39)//rightarrow
  {
   //your logic for right arrow press
  }
});

Upvotes: 0

luek baja
luek baja

Reputation: 1674

This should work:

var x = 0;
document.addEventListener("keydown", event => {
  //every time a key is pushed, this function will fire
  event.code === "ArrowLeft" && moveLeft();
  event.code === "ArrowRight" && moveRight();
});

$("#right-arrow").click(function() {
  moveRight();
});
$("#left-arrow").click(function() {
  moveLeft();
});

function moveLeft() {
  if (x > 0){
    x = x - 1;
    $("#wrapper").animate({ top: '+=400px' }, 1000);
  }
}
function moveRight() {
  if (x < 3){
    x = x + 1;
    $("#wrapper").animate({ top: '-=400px' }, 1000);
  }
}

Upvotes: 1

Related Questions