Maintain Scroll Position for the whole page after Asynchronous Postback

You can use the script mentioned below to maintain the scroll position of the Gridview, Div or Panel that is inside an Update panel. This script can also be used to maintain position of whole page when an AJAX update panel is used. Normally, if the update panel posts back, the item will scroll back to the top because it has been reloaded. In order to solve the problem you have to remember the Horizontal and Vertical scroll position of the element.

To use this script to maintain scroll position of elements within AJAX update panel, do the following:

1) Place the script after the ScriptManager on your page.  As the _endRequest event of the PageRequestManager executes before the page is rendered, the elements will not move.

<script type=”text/javascript”>
var xPos, yPos;
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(EndRequestHandler);

function BeginRequestHandler(sender, args) {
xPos = $get(‘elementName’).scrollLeft;
yPos = $get(‘elementName’).scrollTop;
}

function EndRequestHandler(sender, args) {
$get(‘elementName’).scrollLeft = xPos;
$get(‘elementName’).scrollTop = yPos;
}
</script>

To use this script to maintain scroll position of whole page, do the following:

1) Place this script in the head section of the page, or in the ContentPlaceHolder for head  in case you are using master page.

<script type=”text/javascript”>
var xPos, yPos;
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(EndRequestHandler);

function BeginRequestHandler(sender, args) {
xPos = document.body.scrollLeft;
yPos = documnet.body.scrollTop;
}

function EndRequestHandler(sender, args) {
document.body.scrollLeft = xPos;
document.body.scrollTop = yPos;
}
</script>

—–

Please comment if you find this script useful or if you have any queries.

About these ads

3 thoughts on “Maintain Scroll Position for the whole page after Asynchronous Postback

  1. Referring to your guide:”in the ContentPlaceHolder for head in case you are using master page.”

    I am using master page and i can’t find any head tag in my asp:content. can you please help? Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s