Monday, February 6, 2012

Ajax Update Panel Scroll to Top Issue

I found this great post on how to force a scroll to top when you have a long page that is contained inside an UpdatePanel. For myself, I was having issues with items inside a Wizard control. Some of the pages had very long text. So when the user clicked "Next" it would move to the next page, but it would go the middle of the page (whereever the last page position was) rather than go to the top. So the user would be confused as to where they were. So I wanted the page to go to the top of the page on the Next button click. I added the following script just after my script manager:

<script type="text/javascript" language="javascript">

var postbackElement;
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded)

function beginRequest(sender, args) {
postbackElement = args.get_postBackElement();
}

function pageLoaded(sender, args) {
if (typeof (postbackElement) === "undefined") {
return;
}

if ((postbackElement.id) === "btnStepNext" || (postbackElement.id) === "btnStepPrevious") {
window.scrollTo(0, 0);
}
}

</script>

Then I set the Next and Previous button in the Wizard control to ClientIDMode="Static" so the Javascript could identify them and it worked great!