2

I have a switch statement in which I try to map keyboard shortcuts to a horizontal full page scrolling:

  • Space Bar or Page Down or Right Arrow scrolls forward
  • Page Up or Left Arrow scrolls backward
  • Home or Up Arrow goes to the beginning of the page
  • End or Down Arrow scrolls to the end of the page

Here is my attempt, which isn’t working:

switch (event.code) {
  case "Space" || "PageDown" || "ArrowRight": {
    scrollAmount += window.innerWidth
    break
  }
  case "PageUp" || "ArrowLeft": {
    scrollAmount -= window.innerWidth
    break
  }
  case "Home" || "ArrowUp": {
    scrollAmount = 0
    break
  }
  case "End" || "ArrowDown": {
    scrollAmount = container.scrollWidth
    break
  }
}

How do I propely use the operators in this case?

Tzar
  • 5,132
  • 4
  • 23
  • 57
  • Use the fall-through feature of the switch statement. A matched case will run until a break (or the end of the switch statement) is found. You need to define all cases. – Swapnil N Nov 06 '19 at 14:00
  • I had my answer typed up just before the question was closed as duplicate. I'd like to share it via a codepen, anyway: https://codepen.io/Connum/pen/JjjLVKJ?editors=1111 – Constantin Groß Nov 06 '19 at 14:03

1 Answers1

2

You should specify each case separately:

switch (event.code) {
  case "Space":
  case "PageDown":
  case "ArrowRight": {
    scrollAmount += window.innerWidth
    break
  }
  case "PageUp":
  case "ArrowLeft": {
    scrollAmount -= window.innerWidth
    break
  }
  case "Home":
  case "ArrowUp": {
    scrollAmount = 0
    break
  }
  case "End":
  case "ArrowDown": {
    scrollAmount = container.scrollWidth
    break
  }
}
Andy
  • 61,948
  • 13
  • 68
  • 95