Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

James Rush
PLUS
James Rush
Courses Plus Student 256 Points

Anyone know how to restore users scroll position after a browser restart?

Hello, I am trying to restore a user's scroll position on long articles when they return to the page even if that is a week from now and after a browser restart. The code below is all I have so far it brings me back to where I was on a reload but as soon as I go to another page and back it's all lost and takes me to the top again. Any help would be great, thank you.

if(typeof(Storage) !== "undefined") {

            var storedResult = localStorage.getItem("location");
            var storedURL = localStorage.getItem("url");

             if (storedURL !== 'undefined' && storedResult !== null) {


                if (storedResult !== 'undefined' && storedResult !== null) {

                    $(window).scrollTop(storedResult);
                }
             }

            $(window).scroll(function () { 
              var scrolledDown = window.scrollY;
                var currentUrl = window.location.href;
                localStorage.setItem("location", scrolledDown);
                localStorage.setItem("url", currentUrl);
            });

        } else {
            // No Web Storage Support.
        }

1 Answer

carriebarnett
carriebarnett
16,732 Points

https://stackoverflow.com/questions/17642872/refresh-page-and-keep-scroll-position

Maybe this stackoverflow discussion might help? I would test to see if the same thing happens in different browsers also.

James Rush
James Rush
Courses Plus Student 256 Points

Hello Carrie, that only seems to be about keeping the scroll position following a page reload. I am trying to save the scroll position of a specific page so that if a user goes to another page and returns using a different link or shuts the site and comes back days later it will still remember and return them to their last scroll position.