In my application I have around 100 stanzas of a poem. Each of these stanzas occupies roughly one view-port height. On the side, I have two buttons. One which should scroll down a stanza, and one that should scroll up a stanza.
However, users can also scroll up and down the document, and so I cannot rely on users running sequentially through the stanza IDs with the buttons.
I intended to write a script to keep a track of stanza the user is at at any given point, and then another script to go up or down a stanza.
So far I have written a function which recognizes when a stanza is in the middle of the screen, and logs were the user is. As all search features etc are animated, it's working fine. works like this:
$(document).ready(function() {
var stanzas = $('.stanza')
var currentStanza = 0;
var i = 1;
while ($(stanzas[i]).position().top < $(window).scrollTop() + quarterHeight) {
currentStanza = i;
i++; }
})
I was intending to couple this function with one that says something like: "Scroll until i iterates", but I can't figure out how to do that. Can you figure out a way to scroll to the next stanza?
Of course other solutions are more than welcome if ye have any.
Save currentStanza as element, not as a number so you can do something like this:
function scrollToNext() {
$(currentStanza).next()[0].scrollIntoView(scrollOptions)
}
But i think this might work too, if you want to keep currentStanza as int:
function scrollToNext() {
$(`.stanza:eq(${currentStanza})`).next()[0].scrollIntoView(scrollOptions)
}
scrollOptions
is object that defines how scroll acts, more info here: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
But you probably want to configure it like this:
var scrollOptions = {
behavior: ‘smooth’,
block: ‘center’
}