Friday, 8 October 2010

ASP.NET/JQUERY - Maintain Scroll Position of DIV (example uses a treeview)


Today I had the task of maintaining the scroll position of an asp:TreeView control. Keeping it short and sweet; here's what I came up with.

I noticed that when rendered in the browser, the TreeView is rendered as a div... and from back in the days of remembering window positions after post backs, I knew this wouldn't be much different.

The solution I was working on used JQuery already and I found it useful to pull out references to server controls using the 'endwith' syntax. You can also get client id's, it doesn't matter to an extent.


Code behind
protected void Page_Load(object sender, EventArgs e)
{
    this.AddEvents();
}
 
private void AddEvents()
{
    ScriptManager.RegisterStartupScript(this, this.GetType(), "Load", "PageLoad();", true);
    this.tvOrganisation.Attributes.Add("onscroll", "saveScrollPosition(this)");
}


In the above code i'm attaching an onscroll event to the Treeview. I'm also adding a form load function in javascript so that I can initialise anything in here.


Page Markup
<script type="text/javascript" src="LOCATION OF JQUERY HERE/jquery-x.x.x.js"> </script>
<script type="text/javascript">
    function saveScrollPosition(div) {
        $("[id$='hdnTVScrollYPos']").val(div.scrollTop);
        $("[id$='hdnTVScrollXPos']").val(div.scrollLeft);
    }
 
    function restoreScrollPosition() {
        $("[id$='tvTREEVIEWNAME']").scrollTop($("[id$='hdnTVScrollYPos']").val());
        $("[id$='tvTREEVIEWNAME']").scrollLeft($("[id$='hdnTVScrollXPos']").val());
    }
 
 
    function PageLoad() {;
        restoreScrollPosition();
    }
</script>
 
 
<asp:HiddenField ID="hdnTVScrollXPos" runat="server" Value="0" />
<asp:HiddenField ID="hdnTVScrollYPos" runat="server" Value="0" />


Here i'm using two hidden fields to hold the values of X and Y. This will maintain throughout postback and uses a cookie-less approach towards maintaining these details. The JavaScript speaks for itself.

No comments: