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?

2
  • 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. Commented Nov 6, 2019 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: codepen.io/Connum/pen/JjjLVKJ?editors=1111 Commented Nov 6, 2019 at 14:03

1 Answer 1

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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.