0

I have built a table component with a list of items in it. By defining hotkeys with the react-hotkeys package, I can navigate through the list with the 'arrow up' and 'arrow down' keys. However, I do have a scroll bar on the right side of the screen. Whenever I use the hotkeys, the screen will scroll at the same time. How can I navigate through items with the hotkey without triggering the scrollbar unless the item is out of the current screen?

ash
  • 1,065
  • 1
  • 5
  • 20
Fangyi Li
  • 41
  • 1
  • 8

1 Answers1

1

You can easily prevent the default browser scroll behavior on the event keydown when the key is arrow up or arrow down. This post explains how to do this.

For your specific needs to disable / enable it whether the table is in the viewport or not, you could check if it is in the event.

const table = document.querySelector('#table-id')

window.addEventListener("keydown", function(e) {
    if(["Space","ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].indexOf(e.code) > -1) {
        const y = table.getBoundingClientRect().y
        if (y > 0 && y < window.innerHeight) { // Table is in viewport.
            e.preventDefault();
        }
    }
}, false);
Mteuahasan
  • 491
  • 2
  • 10