0

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!

umbriel
  • 723
  • 1
  • 7
  • 22
  • What behavior do you want the up/down keys to produce? Scroll to next/previous entry? If so, perhaps you could find the topmost visible `entry` element, then `scrollIntoView` to the next one – salezica Jan 19 '18 at 13:48
  • Hi slezica, thanks for looking into that. I just edited the questions to make that clear. And yes scrollIntoView the next or previous slide (in relation to the current slide) – umbriel Jan 19 '18 at 13:50
  • This should help https://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport. Once you know that element, finding the next one and scrolling to should be easy, given the code you already wrote – salezica Jan 19 '18 at 13:51
  • I'm able to set a class to the most visible slide but the IntersectionObserver sometimes marks two slides to be visible at the same time. Making it quite inconsistent. But with ClickEvent I can be sure to only get one slide position. – umbriel Jan 19 '18 at 14:01
  • When you have 2 visible slides, choose the topmost one. Walk the array of slides, and pick the _first_ that's visible, any other will be further down. – salezica Jan 19 '18 at 14:09
  • I also just realised that the value given from IntersectionRatio is inconsistent when using transform scale on the parent. When the children are perfectly aligned 50/50 on the viewport they should be at the ratio of [0.5] but at scale of 0.78 they are at [0.64] each https://imgur.com/a/ZEZ17 I think I may have found the cultprit – umbriel Jan 19 '18 at 14:33

1 Answers1

1

Use the onkeydown event listener

Keycodes:

  • left = 37
  • right = 39
  • up = 38
  • down = 40
Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252