Scroll position....

Topics: Developer Forum, User Forum
Sep 6, 2007 at 5:39 PM
Edited Sep 6, 2007 at 5:42 PM
I needed to keep scroll position on post back and after a little searching I found http://michaelsync.net/2006/06/30/maintain-scroll-position-of-div-using-javascript-aspnet-20/ and with a little modification it works like a champ.

I added to OnPreRender:

if (!this.Page.ClientScript.IsStartupScriptRegistered("FrozenScrollPosition"))
{
StringBuilder sbuScript = new StringBuilder();
sbuScript.AppendLine("window.onload = function(){");
sbuScript.AppendLine("var strCook = document.cookie;");
sbuScript.AppendLine("if(strCook.indexOf(\"!~\")!=0){");
sbuScript.AppendLine("var intS = strCook.indexOf(\"!~\");");
sbuScript.AppendLine("var intE = strCook.indexOf(\"~!\");");
sbuScript.AppendLine("var strPos = strCook.substring(intS+2,intE);");
sbuScript.AppendLine("document.getElementById(\"" + string.Format( CultureInfo.InvariantCulture, "_gv{0}_div", this.ClientID) + "\").scrollTop = strPos;");
sbuScript.AppendLine("}");
sbuScript.AppendLine("}");
sbuScript.AppendLine("function SetDivPosition(){");
sbuScript.AppendLine("var intY = document.getElementById(\"" + string.Format( CultureInfo.InvariantCulture, "_gv{0}_div", this.ClientID) + "\").scrollTop;");
sbuScript.AppendLine("document.cookie = \"yPos=!~\" + intY + \"~!\";");
sbuScript.AppendLine("}");
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "FrozenScrollPosition", sbuScript.ToString(), true);
}


and to Render:

writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "SetDivPosition()", false);


I thought this might be of use to someone or maybe a good addition to the project.