Home

JavaScript Maintain Scroll Position PostBack

The TLDR

<script>

document.getElementsByTagName("body")[0].onscroll = function() {
     sessionStorage.setItem("MyScroll", window.scrollY)
}

document.getElementsByTagName("body")[0].onload = function() {
     window.scrollTo(0, sessionStorage.getItem("MyScroll"))
}

</script>

The Explanation

Jeez again another thing made so goddam bleeding hard by some coders.

     document.getElementsByTagName("body")[0]

I reckon means get the body by it's tag name. I'm not sure why we need the [0] part but I have to assume when we get the tag body it comes as some sort of array, and, errr, we need the first value of the array.

     .onscroll = function()

So we have the body and .onscroll asks JavaScript to do "catch" any scrolling of the body section. As the body is everything visible on the page well then it's the page innit. If there is a scroll then do this following function

     {
         sessionStorage.setItem("MyScroll", window.scrollY)
     }

Here we are going to use sessionStorage. We create or update a space in the browser's sessionStorage called MyScroll and we put in the value of how far we have scrolled in the Y value, Y being up and down like your old high school graphs. Guess what, scrollX would be left-right.

Now whenever the user scrolls up and down we store a value of the scroll position in a nugget of space in the user's browser. Then the user hits "Submit" and the page refreshes. At this point the body's onload option can be found and called.

document.getElementsByTagName("body")[0].onload = function() {
     window.scrollTo(0, sessionStorage.getItem("MyScroll"))
}

So we find the body by tag name, refer to it's onload option then run a function. In the function we window.scrollTo(0, sessionStorage.getItem("MyScroll")) which means "scroll down the window to the value that was stored just before the page was posted and refreshed"

 

 

Reader's Comments

Post Your Comment Posts/Links Rules

Name

Comment

Add a RELEVANT link (not required)

Upload an image (not required)

No uploaded image
Real person number
Please enter the above number below




Home
Admin Ren's Biking Blog