0

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.

Tadgh
  • 19
  • 7

1 Answers1

0

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’
}
BorisTB
  • 1,686
  • 1
  • 17
  • 26
  • I've gotten the integer solution working nicely, which is amazing - but I can't find a way to offset scrollIntoView. Is there a way you know of? scrollIntoView(true) scrolls to the top of the stanza, whereas I intend to scroll it to the center of the page. – Tadgh Aug 14 '19 at 00:02
  • I’ve updated my answer with info on how to set vertical alignment to center – BorisTB Aug 14 '19 at 04:50
  • Thanks so much @Boris :) – Tadgh Aug 14 '19 at 15:52