Maintain Scroll Position of DIV using JavaScript – ASP.NET 2.0

Some people have some problems in maintaining the position of the DIV. Initially, The most of people are using htc for solving this problem. but there are so many disadvantages of using htc such as it works only in Internet Explorer, it doesn’t work properly with Visual Studio 2005 and so on.

Finally, I got the solution for solving this problem.. Using Javascript for keeping the scroll position is the best way to go.. JavaScript helps us to know the current position of DIV. Plus, we can use HTTP Cookie for storing the value of the previous position of DIV tag.

SouceCode Download :

window.onload = function(){
var strCook = document.cookie;
var intS = strCook.indexOf("!~");
var intE = strCook.indexOf("~!");
var strPos = strCook.substring(intS+2,intE);
document.getElementById("grdWithScroll").scrollTop = strPos;
function SetDivPosition(){
var intY = document.getElementById("grdWithScroll").scrollTop;
document.title = intY;
document.cookie = "yPos=!~" + intY + "~!";

I have tested this code with IE6, 7 and Mozilla Firefox. It’s working very fine.
Please let me know if you have any problem with this coding. Thank you.
Special Thanks to Jim Ross and Eric Pascarello.

UPDATED Maintain Scroll Position of DIV using ASP.NET Ajax by Brad Alcock (Thanks for sending this mail, Brad.)

hi. here’s the code with a very brief explanation on what goes on behind the scenes.

a little different to what you did, but sort of on the same track. I’m sure you can find a method of working around it to fit in with your post ^^

right, my div’s id was panel1, I basically created a cookie for the onscroll of the div in the function SetDivPosition(). the read cookie is read using the stringbuilder in the C# Page_load code underneath.

function SetDivPosition(){
var intY = document.getElementById("Panel1").scrollTop;
var date = new Date();
var expires = "; expires="+date.toGMTString();
document.cookie = "cookie1"+"="+intY+expires+"; path=/";
document.title = intY;
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca&#91;i&#93;;
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
return null;

here is the string builder in the page Load. the part in the if(!IsPostback) is there so that when the page is loaded for the very first time, it removes any possibility of a cookie being there (incase the page is returned to within an hour. ) that means the scrollbar will not suddenly jump to a position at arb times like first time page is loaded.
don't forget to use  System.Text; otherwise it will throw an error.

&#91;sourcecode langague="csharp"&#93; 
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
StringBuilder sbScript = new StringBuilder();
sbScript.Append("<script language='JavaScript' type='text/javascript'>");
sbScript.Append("document.cookie = cookie1 + \"=\" + \"\" + -1 + \"; path=/\";");

// Make use ScriptManager to register the script
ScriptManager.RegisterStartupScript(this, this.GetType(), "@@@@MyCallBackAlertScript", sbScript.ToString(), false);

StringBuilder sbScript1 = new StringBuilder();
sbScript1.Append("<script language='JavaScript' type='text/javascript'>");
sbScript1.Append("var strCook = readCookie(\"cookie1\"); "+
"document.getElementById(\"Panel1\").scrollTop = strCook;");

// Make use ScriptManager to register the script
ScriptManager.RegisterStartupScript(this, this.GetType(), "@@@@MyCallBackAlertScript", sbScript1.ToString(), false);


* Maintain Scroll Position in any Page Element
* Remember a Div’s Scroll Position

125 Replies to “Maintain Scroll Position of DIV using JavaScript – ASP.NET 2.0”

  1. Hello Jayjay,

    Have you tried Brad’s code? He wrote the code at page_load event and He added “path” in cookies. Can you tried to do that? sometimes, path is important..

  2. This solution works really well for me!

    Create a public class :-


    Public Class Scripts

    Public Function LoadScroll(ByVal panel As Panel) As String

    Dim sb As New StringBuilder

    sb.AppendFormat(“var scrollTop{0};”, panel.ClientID)

    sb.AppendFormat(“var scrollLeft{0};”, panel.ClientID)

    sb.AppendFormat(“Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler{0});”, panel.ClientID)

    sb.AppendFormat(“Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler{0});”, panel.ClientID)

    sb.AppendFormat(“function BeginRequestHandler{0}(sender, args)”, panel.ClientID)


    sb.AppendFormat(“var elem=document.getElementById(‘{0}’);”, panel.ClientID)

    sb.AppendLine(“if (elem)”) ‘added

    sb.AppendLine(“{“) ‘added

    sb.AppendFormat(“scrollTop{0}=elem.scrollTop;”, panel.ClientID)

    sb.AppendFormat(“scrollLeft{0}=elem.scrollLeft;”, panel.ClientID)

    sb.AppendLine(“}”) ‘added


    sb.AppendFormat(“function EndRequestHandler{0}(sender, args)”, panel.ClientID)


    sb.AppendFormat(“var elem=document.getElementById(‘{0}’);”, panel.ClientID)

    sb.AppendLine(“if (elem)”) ‘added

    sb.AppendLine(“{“) ‘added

    sb.AppendFormat(“elem.scrollTop=scrollTop{0};”, panel.ClientID)

    sb.AppendFormat(“elem.scrollLeft=scrollLeft{0};”, panel.ClientID)

    sb.AppendLine(“}”) ‘added


    Return sb.ToString

    End Function

    Public Sub LoadScroll(ByVal panel As Panel, ByVal page As Page)

    Dim s As String = LoadScroll(panel)

    If Not page.ClientScript.IsStartupScriptRegistered(panel.ClientID) Then

    page.ClientScript.RegisterStartupScript(page.GetType, panel.ClientID, s, True)

    End If

    End Sub

    End Class


    Then call it from the page where the panel in this instance is panel6

    Dim vLoadScroll As New Scripts
    Dim vLoadPanel As String = vLoadScroll.LoadScroll(Panel6)
    ScriptManager.RegisterStartupScript(Me, Me.GetType, “scrollLoad”, vLoadPanel, True)

  3. Nice post Michael. I’ve been looking for this solution for a while now but I really didn’t want to use cookies. Seems like it might be the only way. One question though: Any idea how long the cookie lasts for?

  4. PS. I think the first post from ria was meant to say ‘header row’. I also am interested if you have any tips or tricks for this.

  5. Hi thanks,
    this code is working fine for one grid in a single page.
    If I have two grids in a single page then this code is working only for one grid. Please let me know what Ihave to change in this code, so it works scroll position on both grids

    Prakash Gupta

  6. This is the first code segment that I’ve found that actually works, nice job! I stuck a treeview in instead of a datagrid. The treeview loads data dynamically. The treeview no longer refreshes data though. Any ideas or suggestions would be most appreciated.

    Many many thanks,

    ps -feel free to email me or if you want to look at the code I can send it to you.

  7. Hi
    Thank you very much :) This code works very well..
    Great job..Keep it up :)


  8. hey Micheal,
    iam developing a chat Application,in that im showing ajax based dhtml window having a panel inside a Div,i have used window.settimeout for showing message for every second,here web app is showing inside the windows,only initial login is provided by the windows app and i have to maintain the state of the page,so how to maintain the position of scrollbar for the panel for each second.

  9. If you are having issues deleting and recreating the cookie during page load,

    Use this within the (if !IsPostBack)


    Response.Cookies.Add(new HttpCookie(“cookie1”, “Scrollbar State”));

  10. This cookie code for maintaining the div scroll has worked for me thanx for that, but this code won’t be working if cookies are disabled right? or will it?

  11. nice, but let’s say if i have a few div in a page which i would like to retain their different positions, how to handle/do it then?

  12. what i did is this:
    window.onload = function(){
    var strCook = document.cookie;
    var intS= strCook.indexOf(“!~”);
    var intE= strCook.indexOf(“~!”);
    var intS2=strCook.indexOf(“|^”);
    var intE2=strCook.indexOf(“^|”);
    var strPos= strCook.substring(intS+2,intE);
    var strPos2= strCook.substring(intS2+2,intE2);
    document.getElementById(“Div1”).scrollTop = strPos;
    document.getElementById(“Div2”).scrollTop = strPos2;
    function SetDivPosition(){
    var intY = document.getElementById(“Div1”).scrollTop;
    document.title = intY;
    document.cookie = “yPos=!~” + intY + “~!”;
    function SetDivPosition2(){
    var intY2 = document.getElementById(“Div2”).scrollTop;
    document.title = intY2;
    document.cookie = “yPos=|^” + intY2 + “^|”;

    i could only see that Div1 works, but not Div2, do you know what went wrong huh, appreciate someone can help here

  13. thanks buddy it worked for me. if you have problem with the cookies on the client browser you can use hidden field….

  14. Worked very well with me, I also used it with a data repeater control, works perfectly there… but just wondered… if I add a row to the grid add on the bottom, how can I make it scroll towards the bottom,… Thanks for all the hard work

  15. Very Nice logic really very much appreciated for your work…

    As i have also used gridview in which i have lot of data for which i set overflow=auto..
    and also kept this gridview inside some div

    but the problem is when i scroll the grid and click on the last row than it moves back to its origninal state……

    i have wasted my 4 hrs seriously and not get the right solution as well ….but whn i found your article its hip hip hurray………….

    the script that u have provided is awesome……………

Leave a Reply