Arms crossed picture of James Auble
finger things clup from the office show

Prevent Scroll & Save Scroll Position With Mobile Menu

PublishedOct 15th, 2021

It’s one of those finer touches to the user experience of a site that is sometimes overlooked: You activate the mobile menu, back out because you don’t see what you want— only to find yourself at a new position on the page (usually back up at the top).

There are several tried-and-true methods for displaying a mobile menu overlay on a site, but because you’ve found your way to this article, I will assume you used something like overflow-y: hidden on the <body> and now find yourself being brought back to the top upon deactivating the menu overlay.

First-world problems…I know.

Nonetheless, us web assassins keep a tight ship.

Let’s clean this up.

The key to remembering our location on the page is by accessing window.scrollY, a read-only DOM API that tells us the distance we have scrolled from the top of the page (MDN Docs).

The psuedo-psuedo code is basically this:

  1. When user activates mobile menu first save our scroll position to a variable.
  2. Apply CSS properties overflow-y: hidden and height: 100vh to the <body>.
  3. When user closes the menu, first revert those CSS properties to whatever they were before, commonly overflow: visible and height: auto.
  4. Immediately next in our code, we will scroll the user back to the position they were at using the window.scrollTo(x-coord, y-coord) method.

If all goes well, the user will never know we did any of this in the background because they’re brought back right to where they expected to be!

Here is an implementation of this approach using Alpine.js for simple toggling of our mobile menu state.

Code on web assassins!

Need a web developer?

Contact Me
Back to Blog
Scrolldown Icon