Several steps in the band: pick the nearest to the middle
A wrong answer that prints no error: "the last step reported" is wrong at 0, 100 and is only right by luck at 160 and 330. At 280 there is no earlier scroll, so the first report is the answer.
One chart, many states: each step of the story is a named state, and the chart is a function of the active step. That is why scrolling back up, jumping with a link, resizing and opening the page half-way down all work without special cases.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Add a state weekend to the library that shows the season bands and marks nothing, and call show("weekend", 0) in a scratch copy of the first example. Say what you had to change besides the STATES entry.
Write closestStep(centres, mid) that returns the index of the centre nearest mid and the lowest index on a tie. Test it with an empty list, one centre and a tie.
Explain it without notes
Why define each step as a full state instead of a change from the previous step?
What happens to a running transition when a newer one starts on the same element, and what must your code do about end()?
What does the observer report when a link jumps from step 0 to step 4, and what with smooth scrolling?
Why is the last reported step not always the active one, and how do you choose?
Preview
Console
Nothing logged yet.Expected console output
scrollTop 0 | in the band: [1,2] | last reported: 2 | closest to middle: 1 | really in the middle: 1
scrollTop 160 | in the band: [3,4] | last reported: 4 | closest to middle: 4 | really in the middle: 4
scrollTop 100 | in the band: [2,3] | last reported: 2 | closest to middle: 3 | really in the middle: 3
scrollTop 330 | in the band: [5,6] | last reported: 6 | closest to middle: 6 | really in the middle: 6
opened at scrollTop 280, first report: 5