Search code examples
javascriptwebflow

Triger Next Prev function button when clicking the left right key


good day everyone... badly needed help how can I trigger the next prev function if I press the left and right arrow keys. this is for the slider/lightbox that I was assign into.

this is the code

$(document).ready(function() {
  var currentIndex = 0,
    navItems = $(".navindex");

  function setSlide(index) {...}

  $(".navindex").click(function() {
    var index = $(".navindex").index($(this));
    currentIndex = index;
    setSlide(currentIndex);
  });


  function next() {
    if (currentIndex < navItems.length - 1) {
      currentIndex++;
      setSlide(currentIndex);
    }
  }

  $(".next").click(function() {
    next();
  });

  function prev() {
    if (currentIndex > 0) {
      currentIndex--;
      setSlide(currentIndex);
    }
  }

  $(".prev").click(function() {
    prev();
  });


  function slide() {
    if (currentIndex < navItems.length - 1) {
      currentIndex++;
      setSlide(currentIndex);
    } else {
      currentIndex = 0;
      setSlide(currentIndex);
    }
  }

});


Solution

  • You want to handle key events. Something along the lines of:

    $(document).keyup((evt) => {
      if (evt.key === 'ArrowLeft')
        return prev();
      if (evt.key === 'ArrowRight')
        return next();
    });