Div Scroll Position

Sometimes when creating scrollboxes, you might want the scrollbar to maintain its position when the user navigates away from, then returns to the page.

For example, say you have a link halfway down the scrollbox. The user clicks on the link - which opens a different webpage - then the user clicks the "Back" button to continue reading the rest of the contents of the scrollbox. When this happens with a normal scrollbox, the scrollbar will be back at the top of the scrollbox. In other words, the user will need to scroll back down to see the link they clicked on previously. This could become annoying, especially if there are many links. The code on this page overcomes this problem.

First, here's an example of what I mean.

Quick Example

The following code is basically what the above example uses. I've simplified it a little so that it's easier to understand. The only difference is that the above example uses functions for the JavaScript.

The above code uses JavaScript combined with a hidden form field to remember the position of the scrollbar. The onload event handler is added to the <body> tag to trigger some JavaScript. This JavaScript sets the <div>'s scrollbar to the position that is held in the hidden form field (specified by using the <input> tag).

Adding JavaScript Functions

The following code includes the JavaScript functions. This is the same code that is used in the example.

Multiple Scrollboxes

The above code is great if you only have one scrollbox. But if you have more than one scrollbox on your page, the code will need to be adjusted. Each scrollbox will need to have its own ID and hidden form field, and the JavaScript functions will need to recognize this and deal with it.

Here's an example of a page with more than one scrollbox. On that page, the code has been changed to cater for multiple scrollboxes.

And here's the code for that: