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

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
*/

124 thoughts on “Maintain Scroll Position of DIV using JavaScript – ASP.NET 2.0

  1. Reply Michael Sync Apr 4,2008 7:37 pm

    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. Reply Dave Apr 4,2008 8:39 pm

    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)

  3. Reply Bala May 1,2008 1:57 am

    You are great that works like a charm………

  4. Reply Mitch May 22,2008 7:35 am

    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?

  5. Reply Mitch May 22,2008 7:44 am

    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.

  6. Reply Prakash Gupta Dec 4,2008 4:58 am

    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

  7. Reply Bob Feb 26,2009 6:53 pm

    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.

  8. Reply Bob Feb 26,2009 7:38 pm

    Nevermind, I figured it out…just me being a doofus:)

  9. Reply Karl Apr 13,2009 4:02 pm

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

  10. Reply Mahendranath Apr 28,2009 3:35 am

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

    Cheers,
    Mahendra

  11. Reply ayyamperumal Jul 23,2009 6:40 am

    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.

  12. Reply Ghulam Haider Jul 30,2009 2:11 am

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

  13. Reply Andy Stringer Aug 20,2009 3:10 pm

    Perfect! Thanks for posting your code. Make sure to call SetDivPosition in your div. I did it in my Panel like this:

  14. Reply tsloan Nov 13,2009 11:14 am

    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”));

  15. Reply Adil Hafiz Dec 25,2009 11:13 am

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

  16. Reply soumiek ranjan chakravarty Feb 1,2010 5:43 am

    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?

  17. Reply GeronimoRumplestiltskin Feb 16,2010 2:51 pm

    Thanks, man. You’re a life-saver.

  18. Reply martin Apr 25,2010 7:14 pm

    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?

  19. Reply martin Apr 25,2010 8:27 pm

    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

  20. Reply vikas Aug 10,2010 2:19 pm

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

  21. Reply Abhijeet Khake May 16,2011 5:32 am

    Hello, Nice post !

    problem while using dynamically created grid on every postback, i am using below code to create scrollable div

    http://www.aspsnippets.com/Articles/Dynamically-
    freeze-ASP.Net-Gridview-header-using-JavaScript.aspx

    any idea how to use with this

    abhijeet

  22. Reply dINESH Aug 17,2011 6:25 am

    Great.
    Thanks.

  23. Reply amiya Apr 10,2012 11:47 pm

    sir i want the grid with scrolable and fixed header

  24. Reply Santhosh Raviendranath Aug 28,2012 5:10 am

    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

Leave a Reply