Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Redirect to the previous page and keep the scroll position

I have seen this question where you can redirect to the previous page using:

return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

but is there a way to also keep the scroll position that it was at? The above reloads the page afresh.

like image 450
Anupam Avatar asked Oct 19 '25 04:10

Anupam


1 Answers

After some back and forth, this is what I came up with (with help from this answer):

from django.http import HttpResponse

def myview (request):
  ..
  ..
  return HttpResponse('<script>history.back();</script>')

Also, keep in mind that history.back() does not 'reload' the page. To also reload the page, we have to use location.reload() which also keeps the scroll position but we have to use it in a clever way so as not to let it go into an infinite loop. So this is what I did to get around it (as mentioned in this clever answer)

<input type="hidden" id="refreshed" value="false">
<script type="text/javascript">
    $(window).load(function(){
        if ($('#refreshed').val() == "false") {
          $('#refreshed').val("true"); 
        }
        else {
          $('#refreshed').val("false");
          location.reload();
        }
      });
</script>

Note: The above is using a hidden input field because the state of the input field would retain when 'back' is invoked.

All that said, you may want to consider doing an Ajax call if that works better in your use case instead of doing the above.

like image 132
Anupam Avatar answered Oct 21 '25 20:10

Anupam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!