in ASP.NET

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 : http://michaelsync.net/demo/MaintainScroll.zip

window.onload = function(){
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("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();
date.setTime(date.getTime()+(1*60*60*1000));
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[i];
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.

 
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=/\";");

sbScript.Append("</script>");
// 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;");
sbScript1.Append("</script>");

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

Regards,
Brad

/*References
*
* Maintain Scroll Position in any Page Element
* http://authors.aspalliance.com/jimross/Articles/MaintainScrollPos.aspx
*
* Remember a Div’s Scroll Position
* http://radio.javaranch.com/pascarello/2005/07/18/1121709316718.html
*/

Leave a Reply

123 Comments

  1. 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.Append(“{“)

    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.AppendLine(“}”)

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

    sb.AppendLine(“{“)

    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

    sb.AppendLine(“}”)

    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)

  2. You are great that works like a charm………

  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

    thanks
    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,
    Bob

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

  7. Worked great for me, many thanks for taking the time to post this information.
    kind regards.

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

    Cheers,
    Mahendra

  9. 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.

  10. WoW Excellent solution. You save my 3Hrs of searching on net.

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

    Use this within the (if !IsPostBack)

    Response.Cookies.Remove(“cookie1″);

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

  12. great article…..but what if the user disables cookies in his/her browser????think about it!!!!!!

  13. 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?

  14. 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?

  15. 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

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

  17. 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