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..
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..
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({})
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?
Just building on the other answers here but this is how you could do it:
//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);
}
});