2

I want to scroll to top if there is an error on postback of a button click. I am working on asp.net C#. I am using following method to scroll to top.

.cs code on page_load method

if (IsPostBack)
{
    System.Web.UI.ScriptManager.RegisterStartupScript(Page, this.GetType(), "ScrollPageLogin", "ResetScrollPositionLogin();", true);
}

.ascx code for jquery call

function ResetScrollPositionLogin()
{
   $('html, body').animate({ scrollTop: 0 }, 'fast');
}

When I use this code and click on login button then it scroll to the down first and then scroll to up. Please help me to resolve this.

Jonathan
  • 6,507
  • 5
  • 37
  • 47
Developer
  • 1,435
  • 2
  • 23
  • 48
  • Where is the page position with no scroll changes? If you take out your animation is the page position at the top already or is it at a '#' link position somewhere? – user2782001 May 08 '15 at 23:38
  • by default page position is the middle of page. So when i set the page position to top it first goest to the default and then animate to top. – Developer May 08 '15 at 23:41
  • And you want the page to skip the middle and just load with the top part of the page in view,? – user2782001 May 08 '15 at 23:46
  • Yes.. When i click on login link and if there is any error while postback I want to scroll the page to top so User can see the error. – Developer May 08 '15 at 23:51
  • Test something. Skip jquery for now. Just add window.addEventListener('load',function(){document.documentElement.scrollTo(0,0)}) into a script tag in the head and see what happens (unless you are using ajax then don't use window load use your ajax success/failure methods). – user2782001 May 08 '15 at 23:52
  • Hi thanks for the reply I tried it but its not working.. – Developer May 08 '15 at 23:56

1 Answers1

1

Well, many browsers have smart surfing, which means they can remember things like page position and form input without being told to. This has been addressed by some at stack already

Another really hacky way of doing it is to set the body of your page to display:none and then use jquery show() or plain javascript to set the display to block after your content has loaded. Hides any jumping of page position but not ideal design to say the least.

Community
  • 1
  • 1
user2782001
  • 3,380
  • 3
  • 22
  • 41