I have a Django template where I call a view by clicking a button. The view function returns a HttpResponseRedirect
to the same page. I want the page to return/refresh to the same scroll position as when the user clicked the button.
Here's what I've tried so far:
Attempt 1: Based on this and this, I added an onsubmit
to the form as follows:
<form action="{% url 'buy' market.id %}" method="post" onsubmit="return refreshToSameScroll()">
...calling location.reload()
through the following script:
<script type="text/javascript">
function refreshToSameScroll() {
location.reload();
}
</script>
But that didn't work.
Attempt 2: I then tried the following combination, reworked from this:
<form action="{% url 'buy' market.id %}" method="post" onsubmit="return saveScroll()">
...with this script:
<script type="text/javascript">
function saveScroll () {
var page_y = document.getElementsByTagName("body")[0].scrollTop;
window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
}
window.onload = function () {
if ( window.location.href.indexOf('page_y') != -1 ) {
var match = window.location.href.split('?')[1].split("&")[0].split("=");
document.getElementsByTagName("body")[0].scrollTop = match[1];
}
}
</script>
The idea here being that clicking the button saves the scroll position, which then gets picked back up once the page reloads/refreshes. But that didn't work either.
Any idea what I'm doing wrong?