Click here to Skip to main content
Licence CPOL
First Posted 18 Mar 2008
Views 44,058
Bookmarked 24 times

Persisting the scroll position of a DIV on AJAX postbacks

By | 18 Mar 2008 | Article
This article explains how you can persist the scroll position of a DIV in AJAX postbacks.

Introduction

By default, the scroll position of DIV tags will be reset whenever you do a postback with AJAX. The following code can be used if you're working with AJAX and DIV-tags and you need to persist the scroll position of your DIV tag whenever an AJAX-postback occurs. I used the code in my own project, where I had to have an UpdatePanel and a GridView inside a fixed DIV-tag, while persisting the scroll position on Edit/Cancel/Update commands.

The code has been tested with IE6, IE7, FF 2.0.0.12, and Opera 9.26, and should basically work with any browser supporting the document.getElementById() method.

Background

I recently came across the prescribed problem above. So, I Googled and found an article on CodeProject (Persisting the scroll position of child DIV’s using MS AJAX) - however, the provided solution didn't work for me, so I decided to implement my own solution.

Using the code

Add the following code between your <head></head> or your <body></body> tags:

<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
    setScrollPos();
} 
function saveScrollPos(){
    document.getElementById("scrollPos").value = 
             document.getElementById("divScroll").scrollTop;
}
function setScrollPos(){
    document.getElementById("divScroll").scrollTop = 
             document.getElementById("scrollPos").value;
}
</script>

NB! You might have to change the scrollPos name with the ClientID if your element is encapsulated in another control, MasterPage, UpdatePanel etc. You can get the ClientID like this:

public static string scrollPos = String.Empty;

protected void Page_Load(object sender, EventArgs e){
  scrollPos = ((HtmlInputHidden)scrollPos).ClientID.ToString();
}

Then, change the JavaScript to:

<script type="text/javascript" language="javascript">
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler(sender, args) {
    setScrollPos();
} 
function saveScrollPos(){
    document.getElementById("<%=scrollPos%>").value = 
                document.getElementById("divScroll").scrollTop;
}
function setScrollPos(){
    document.getElementById("divScroll").scrollTop = 
                document.getElementById("<%=scrollPos%>").value;
}
</script> 

Assuming that you have already added a <asp:ScriptManager> to your page, add the following:

<input type="hidden" id="scrollPos" name="scrollPos" value="0" runat="server"/>

<asp:UpdatePanel runat="server" ID="up1" UpdateMode="always">
<ContentTemplate>
<asp:Button runat="server" ID="button1" text="Post back!" />

<div id="divScroll" onscroll="saveScrollPos();" 
        style="height: 200px; overflow:auto; overflow-x:hidden; overflow-y:scroll;" >

</div>

</ContentTemplate> 
</asp:UpdatePanel>

Points of interest

The trick that made the code work compared to other resources I have looked at was the endRequest - see more here: PageRequestManagerEndRequestEvent.

Updates

  • 19-3-2008 - Fixed a couple of typos :-)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

perels



Denmark Denmark

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralSweet! PinmemberMember 29253152:01 8 Feb '12  
GeneralRe: Sweet! Pinmemberperels18hrs 10mins ago 
GeneralThanks!! Pinmemberyonatankr20:21 16 Aug '09  
GeneralRe: Thanks!! Pinmemberperels18hrs 10mins ago 
QuestionHow to reset the scroll positon back to zero? Pinmemberbentonbenton12:19 12 May '09  
AnswerRe: How to reset the scroll positon back to zero? Pinmemberbentonbenton12:34 12 May '09  
GeneralRe: How to reset the scroll positon back to zero? Pinmemberperels12:03 21 Jul '09  
GeneralExcellent - Thank you Pinmemberthelizard8:52 2 May '09  
GeneralRe: Excellent - Thank you Pinmemberperels11:58 21 Jul '09  
GeneralThis is fantastic PinmemberSergodtud9:19 18 Mar '09  
GeneralRe: This is fantastic Pinmemberperels11:55 21 Jul '09  
GeneralCouple tweaks Pinmembermaxismclaren11:02 9 Jan '09  
Depending on how much scrolling is done for normal navigation/behavior, it might be good to store the element references because the onscroll event fires almost continuously while scrolling. You might want to handle multiple UpdatePanels as well.
 
If you're mixing in with your markup (like the code above does) it'll look like this:
<script>
var scrollPos = null;
var divScroll = null;
<br>
function scrollInit(shouldReload) {
  if (shouldReload || !scrollPos ) {
    scrollPos = document.getElementById('<%=scrollPos%>');
  }
  if (!divScroll) {
    divScroll = document.getElementById('divScroll');
  }
}
 
function saveScrollPos() {
  scrollPos.value = divScroll.scrollTop;
}
 
function setScrollPos() {
  divScroll.scrollTop = scrollPos.value;
}
 
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
 
function endRequestHandler(sender, args) {
  if (args.get_error() == undefined && sender._postBackSettings.panelID == 'up1') {
    scrollInit(true); //Control reference invalid when redrawn
    setScrollPos();
  }
}
 
function init() {
  scrollInit(false);
}
</br></script>
 
...
 
<body  önload="init()">
</body>

GeneralRe: Couple tweaks Pinmemberperels11:58 21 Jul '09  
GeneralThanks PinmemberSaeedses0:01 30 Jun '08  
GeneralRe: Thanks Pinmemberperels4:39 11 Jul '08  
GeneralGreat Pinmembermerlin9815:36 19 Mar '08  
GeneralRe: Great Pinmemberperels7:03 19 Mar '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 18 Mar 2008
Article Copyright 2008 by perels
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid