7

In Javascript , Is there any method to maintain current's scroll location after refreshing the page?

It usually show the top of the page after refreshing.. I don't want it..

1
  • 4
    save it before refreshing to localstorage, retrieve it if localstorage exists...
    – EugenSunic
    Commented Aug 7, 2020 at 16:36

3 Answers 3

1

A Django/Javascript solution would be to fire an ajax on Jquery's beforeunload (page refresh function), store the value as a session variable then render it into the template in the GET request.

template

<script type="text/javascript">
$(window).on('beforeunload', function(){
    var scroll_pos = $(document).scrollTop()
    $.ajax({
        url: window.location.href,
        data: {
          'scroll_position': scroll_pos
        },
        dataType: 'json',
    });
});

$(window).on('load', function(){
    $(document).scrollTop({{ request.session.scroll_position }});
});
</script>

views.py

class YourView(TemplateView)
    template_name = "example.html"

    def get(self, request, *args, **kwargs):
       args = {}
       scroll_position = request.session.pop('scroll_position',0)
       args.update({'scroll_position':scroll_position})
       return render(request, self.template_name, args)

    def post(self, request, *args, **kwargs):
       if request.is_ajax:
           request.session['scroll_position'] = request.POST.get('scroll_position')
           return JsonResponse({})
1
  • 1
    I tried the above but using url parameters. It turned out very messy. The above way is far nicer.
    – andyw
    Commented Aug 7, 2020 at 17:27
0

Just building on the other answers here but this is how you could do it:

  1. Save scroll position to local or session storage.
  2. In document.ready you could check if the particular key exists
  3. If it exists you can scroll to retrieved scroll position
//Set scroll position
localStorage.setItem("scroll_position", document.documentElement.scrollTop);

//On document.ready, check if key exists in localStorage
document.ready(function(){
    if(localStorage.getItem("scroll_position" != null) {
        var scrollPosition = localStorage.getItem("scroll_position");
        //Scroll to position
        window.scrollTo(0, scrollPosition);
    }
});

0

You can save current scroll location in localStorage whenever user scroll the page, and then after page refresh when you sure all the DOM created - you can retrieve the location from localStorage and use it: Element.scrollTop = savedLocation

You can also use anchor tags, see this: How to scroll HTML page to given anchor?

Not the answer you're looking for? Browse other questions tagged or ask your own question.