← All Exercises
Cycle Focus Inside a Modal Dialog
intermediatejavascript
Background
A modal must contain keyboard focus; wrapping at both ends keeps users from tabbing into inert page content behind it.
Problem
Write nextFocusIndex(state) that computes focus movement for Tab and Shift+Tab inside a modal, wrapping between the first and last focusable elements.
Input
A JSON string with current index, focusable count, and shift flag.
Output
The next zero-based focus index, or -1 when nothing is focusable.
Sample tests
Sample 1
Input: {"current":3,"count":4,"shift":false}Expected: 0
Sample 2
Input: {"current":0,"count":4,"shift":true}Expected: 3
Sample 3
Input: {"current":1,"count":4,"shift":false}Expected: 2
Sample 4
Input: {"current":0,"count":0,"shift":false}Expected: -1
Sample 5
Input: {"current":0,"count":1,"shift":true}Expected: 0
Your solution
Learning objective
Trap keyboard focus in a dialog with correct wrap-around math for both Tab directions.