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

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..
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)
You are great that works like a charm………
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?
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.
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
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.
Nevermind, I figured it out…just me being a doofus:)
Worked great for me, many thanks for taking the time to post this information.
kind regards.
Hi
,
Thank you very much :) This code works very well..
Great job..Keep it up :)
Cheers,
Mahendra
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.
WoW Excellent solution. You save my 3Hrs of searching on net.
Perfect! Thanks for posting your code. Make sure to call SetDivPosition in your div. I did it in my Panel like this:
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”));
great article…..but what if the user disables cookies in his/her browser????think about it!!!!!!
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?
Thanks, man. You’re a life-saver.
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?
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
thanks buddy it worked for me. if you have problem with the cookies on the client browser you can use hidden field….
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
Great.
Thanks.
sir i want the grid with scrolable and fixed header