Sunday, November 21, 2010

Scrolling to the Top of an Aspx page conditionally

Sounds like a simple task right? Maybe thats why I accepted to help my team mate on this functionality despite being in the middle of a really hectic week. I admit, it took me a little longer than my estimated "10 minutes" to get this to work. It was one LENGTHY "ajaxified" aspx page and the requirement was - to scroll the page to the top IF there were exceptions on save. Apparently there was an error message displayed on top of the page. So IF there were any exceptions on save - the friendly error text gets displayed there. Among many other options suggested and provided, the business users (you know, the people whom we bill our timesheets...) preferred the scroll functionality - because according to them, I quote - "that sounded the easiest". Yeah. Tell me about it!

I tried registering a javascript to scroll the window to co-ords 0,0 - which did not work.

If I made the page to always scroll to the top, then on EACH callback, the page would go right up - which is wrong again. So had to flag it and follow up and on a conditional basis.

For which I had to make the below code changes to get the page to scroll correctly:

Add the following to the markup:
<script language="javascript" type="text/javascript">

var errorEncountered;

errorEncountered = 0;

function scrollTop() {

 if (errorEncountered == 1) {

 Sys.WebForms.PageRequestManager.getInstance().add_endRequest(scrollTop2);

 };

}

function scrollTop2() {

 if (errorEncountered == 1) {

  scrollTo(0, 0);

  errorEncountered = 0;

 };

}
</script>

Add the following to the code behind at the catch of an exception on save:
System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "Script", "errorEncountered=1;scrollTop();", True)