Maintaining Scroll Position of Window After Postback

2011-05-01

You can easily do this in the aspx page by specifying a page attribute like this:
MaintainScrollPositionOnPostback="true"

i.e

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PopUp.aspx.cs" Inherits="MinimizeMaximizeTab.PopUp" MaintainScrollPositionOnPostback="true" %>

But this works in IE only.

Here is the Javascript code for maitaining the window position after postbacks to previous position.

1. First we need 2 hidden variables to store X,Y positions of window during the scroll event & resize events.
2. Then on onload event of window restore the X,Y positions kept in the hidden variables to
window.scrollTo(x, y);

3. Register the javascript events in the page load

I have tested this in Chrome/Firefox/IE and it's working fine!.
Code Behind

----------------
protected void Page_Load(object sender, EventArgs e)

       {



           string codeJavaScript = "<script language=javascript>";

           codeJavaScript += "window.onload = restoreScroll;window.onscroll =saveScroll;onresize =saveScroll;";

           codeJavaScript += "</script>";



           Page.RegisterClientScriptBlock("OnLoadEventAndScrollAndResizeEvents", codeJavaScript);



          

       }
Javascript code -----------------
function saveScroll() {

   var scrollX, scrollY;



   if (document.all) {

       if (!document.documentElement.scrollLeft)

           scrollX = document.body.scrollLeft;

       else

           scrollX = document.documentElement.scrollLeft;



       if (!document.documentElement.scrollTop)

           scrollY = document.body.scrollTop;

       else

           scrollY = document.documentElement.scrollTop;

   }

   else {

       scrollX = window.pageXOffset;

       scrollY = window.pageYOffset;

   }

   document.getElementById('hdnScrollPositionX').value = scrollX;

   document.getElementById('hdnScrollPositionY').value = scrollY;

}







function restoreScroll()

{

var x = document.getElementById('hdnScrollPositionX').value;

var y = document.getElementById('hdnScrollPositionY').value;

window.scrollTo(x, y); 

}
 
Works in following

1 comments:

Anonymous said...

Alveo
Hi there, yes this paragraph is really good and I have learned lot of things from it about blogging.
thanks.