Thursday, August 20, 2009

Reset Scroll Position When Using MaintainScrollPositionOnPostback

If you're using MaintainScrollPositionOnPostback="true" to, well, maintain your scroll position on postback, sometimes you still want to bump the scroll up to the top (if you're using multiple panels or whatever. Here is a nice and easy fix.

1. Put this method in your code-behind:

    private void ResetScrollPosition()
{
if (!ClientScript.IsClientScriptBlockRegistered(this.GetType(), "CreateResetScrollPosition"))
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "CreateResetScrollPosition", "function ResetScrollPosition() {" + Environment.NewLine +
" var scrollX = document.getElementById('__SCROLLPOSITIONX');" +
Environment.NewLine + " var scrollY = document.getElementById('__SCROLLPOSITIONY');" +
Environment.NewLine + " if (scrollX && scrollY) {" +
Environment.NewLine + " scrollX.value = 0;" +
Environment.NewLine + " scrollY.value = 0;" +
Environment.NewLine + " }" +
Environment.NewLine + "}", true);

ClientScript.RegisterStartupScript(this.GetType(), "CallResetScrollPosition", "ResetScrollPosition();", true);
}
}


2. Call ResetScrollPosition(); in any method where you want to reset the scroll position.

No comments:

Post a Comment