umbriel
umbriel

Reputation: 751

JS full page slide navigate with keypress

I'm building a sort of presentation using IntersectionObserver API. And I want to be able to go up/down the slides using the keyboard arrow keys. So far I have managed to make it work on click event. It's easier because I can just ask the interSectionObserver to go to the next sibling on click. But on key press I find the implementation a bit more tricky.

I have a reduced test case on CodePen https://codepen.io/umbriel/pen/ppqLXX

function ioHandler(entries) {
    for (let entry of entries) {
      entry.target.style.opacity = entry.intersectionRatio.toFixed(2);
      entry.target.addEventListener('click', function(e) {
        if (this.nextElementSibling !== null) {
          this.nextElementSibling.scrollIntoView({
            'behavior': 'smooth'
          });
        }
      },true);

      if (entry.intersectionRatio > .5) {
        entry.target.classList.add('active')
      } else {
        entry.target.classList.remove('active')
      }
    }
  }

Thanks!

Upvotes: 0

Views: 152

Answers (1)

Razvan Zamfir
Razvan Zamfir

Reputation: 4614

Use the onkeydown event listener

Keycodes:

  • left = 37
  • right = 39
  • up = 38
  • down = 40

Upvotes: 1

Related Questions