How To: Persisting scroll position in a User Control in ASP.NET and AJAX

A div tag allows you to add scrolling to a user control.  But how do I maintain the position of the scroll on postback or when I return to the page?

The Page attribute MaintainScrollPositionOnPostback only works at the page level, so we need a way to persist scroll positions for a control.

You can use javascript to maintain the scroll position in a cookie and set the scroll position in the postback.  Below is the javascript inside the ascx markup of the user control to make the div scrolling persistent:

<script type="text/javascript">
function GetDivPosition()
{
 
var strCook = document.cookie;
 
if(strCook.indexOf("!~")!=0){
  
var intS = strCook.indexOf("!~");

var intE = strCook.indexOf("~!");

var strPos = strCook.substring(intS+2,intE);

document.getElementById("persistMe").scrollTop = strPos;

}

}

window.onload = function()
{
 
GetDivPosition();
}

function SetDivPosition(){

var intY = document.getElementById("persistMe").scrollTop;

document.title = intY;

document.cookie = "yPos=!~" + intY + "~!";

}

</script>

<div id="persistMe" style="width:720px; height:200px; overflow:auto;" class="PanelBGColorMain" onscroll="javascript:SetDivPosition()" >

After using the javascript for persisting scrolling, I discovered it works fine as long as I don't have to dynamically recreate the control.  If you recreate the control in code and the control sits inside an AJAX update panel, you'll need some way of calling the javascript from within the code.  This is accomplished through the script manager as shown:

ScriptManager.RegisterStartupScript(this, this.GetType(), "myScript3", "GetDivPosition();", true);

The RegisterStartupScript method calls the javascript inside your ascx markup.

If your control is not sitting inside an AJAX panel, you can call RegisterStartupScript from the ClientScriptManager class.

Hope this staves off some of the frusteration I went through in coming up with this solution for the next guy dealing with scrolling of controls.

Ebook Download
View all
Learn
View all