2

So I have a very long div that I need to maintain the scroll-position for when a user submits a form. Since I've never used JavaScript properly before I have no clue as to how to do that. Searching for the answer has not provided a useable answer. What I have gathered is that because I use jQuery, I might be able to use .scrollTop(), but more than that I do not know.

Below a rough sketch of the html page and how it looks:

<html>
<head>
<title>Untitled Document</title>
<style>
#article-text {
    height: 100px;
    overflow: scroll;
}
</style>
</head>
<body>
<div>
Some random text.
</div>
<div id="article-text">
Very, very long text.
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
Even more text.
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
That is how long the text is
</div>
<div class="form-nav">
    <input type="submit" name="add_event" value="Add Event">
</div>

</body>
</html>

On clicking "Add Event", a POST request is sent and the page is reloaded:
views.py

elif 'add_event' in request.POST:

                cp = request.POST.copy()

How do I save the scroll progress in the "article-text" div? Not the whole page, but that div specifically. Would love any pointers here.

LukasKawerau
  • 1,071
  • 2
  • 23
  • 42
  • A better option would be to submit the form with AJAX, so that the page doesn't reload at all... – rnevius Jun 27 '16 at 15:22

2 Answers2

4

You don't have a form on your page, so I am guessing that you are initiating the POST request using JS/jQuery.

Best way: send the request via AJAX.

$.post(url, data, function(response){ /* success */ });

That way you don't need to reload the page and it stays exactly at the scroll position it was before.

If for some reason you need to reload, you can store the current scroll position from .scrollTop() into localStorage and on every page load check localStorage for that value.

To set the value, do it before you submit the form with

localStorage.setItem('my-scroll-pos', $(window).scrollTop());

And after the page reloads, get the value back.

var pos = localStorage.getItem('my-scroll-pos', 0);
if (pos)
    $(window).scrollTop(pos)
C14L
  • 12,153
  • 4
  • 39
  • 52
  • I do have a form, I should have put that in the code above, sorry. I can't use AJAX, sadly, so I have to redirect the user to the same page after submitting the form. Where exactly would I put the `localStorage` part? And does that take the scroll position of that particular div? – LukasKawerau Jun 27 '16 at 16:11
0

You can store the position in localstorage or attach it to the URL. This has already been answered here: Refresh Page and Keep Scroll Position.

Community
  • 1
  • 1
Molly Harper
  • 2,363
  • 3
  • 26
  • 35