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..
During page unload, get the scroll position and store it in local storage. Then during page load, check local storage and set that scroll position.
You can use the location. reload() JavaScript method to reload the current URL. This method functions similarly to the browser's Refresh button. The reload() method is the main method responsible for page reloading.
Bookmark this question. Show activity on this post. I'm running into a problem that's actually a "feature" on Chrome. As most of you might know, Chrome remembers a scroll position that it returns to, whenever you come back to a page.
The JavaScript history API has the scrollRestoration property, which when set to manual, prevents the last scroll location on the page to be restored. You can use it in the following way: For browsers that don't support this, you could create a fallback to using window.onbeforeunload, for example, in the following way:
For browsers that don't support this, you could create a fallback to using window.onbeforeunload, for example, in the following way: Before the page unloads, we can change the scroll position to the top of the page. This would change the browser's last scroll position, and when the page refreshes it would start at the top of the page.
Just add an ID link as a separate parameter in the links HREF tag that links to the top of the div that I want to stay in focus. If you need to navigate to a page with a certain scroll position instead of reloading it, mark an element with an id:
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({})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With