Simple scroll_to_top() function

I thought I’d share a simple scroll_to_top() function for the content panel in case anyone might find it useful.

It’s most basic use case is for scrolling to the top when switching between pages (forms in the content panel of a template form).

Currently, if you have pages with a lot of content, switching between pages would retain the position of the scrollbar. I.e., the new page will load in the middle of the page.

The function below fixes this.

def scroll_to_top():
  content_element = anvil.js.window.document.getElementsByClassName("content")[0]
  content_element.scrollTo(0,0)

You can use it in the on_click events for your nav buttons or the sub-form’s __init__. Although, if you use it in the __init__ it will not work if you have form caching (e.g., from anvil_extra’s hash routing). So I recommend using it inside the nav buttons.

1 Like

And it doesn’t work on mobile for some reason… or at least chrome on android

Ok, this one works on mobile too

def scroll_to_top():
  # scroll "content" dom element to top
  content_element = anvil.js.window.document.getElementsByClassName("content")[0]
  content_element.scrollTo(0,0)
  # scroll "nav-holder" dom element to top
  nav_holder_element = anvil.js.window.document.getElementsByClassName("nav-holder")[0]
  nav_holder_element.scrollTo(0,0)

Update: the code above is for the Rally template. The M3 template works a bit differently and the code for it should be adapted to

def scroll_to_top():
  anvil.js.window.scrollTo(0,0)

Some context: In the Rally template you are scrolling through either the .content div or .nav-holder div depending on the device. In the M3 template you are scrolling through the root html element.