How to correctly use jquery.animate on page scroll after asp.net MaintainScrollPositionOnPostback
I'm trying to make a "Page scrolling animation" occur after the users clicks on my ASP.NET button.
Pretty straightforward approach:
String script = "<script type=\"text/javascript\">" + "\n" +
"$(document).ready(function() {" + "\n" +
"var destination = $('#" + lblMessage.ClientID + "').offset().top;" + "\n" +
"alert($('html, body').scrollTop());" + "\n" +
"$('html, body').animate({ scrollTop: destination-20}, 500 );" + "\n" +
"});" +
"</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "scrollToMessage", script);
This all works except for one thing. My button is below the page fold, so the user has to scroll down to click it. Once he clicks it, my code behind does some Business stuff, then registers the javascript to scroll the page "From where it was to where my label is" (which is just a bit below position zero. But this is not what is happening. My javascript code is getting executed before the scroll position is maintained by ASP.NET so, the scroll animation goes from zero to my label's position, and not from my button's position to my label's position.
And so the whole point of this being lovely is out the window.
So how can I work around this problem, I'm guessing ASP.NET's MaintainScrollPositionOnPostback javascript is executed after my document.ready, I could simply try to delay it, ideally to "queue" it right after the .NET scroll adjustment. But I have no clue how to do that.
Anyone had similar issues? Any hints?
// ### BEGIN SOLUTION ###
Simply had to call manually ASP.NET's WebForm_RestoreScrollPosition(). Clean result.
String script = "<script type=\"text/javascript\">" + "\n" +
"$(document).ready(function() {" + "\n" +
"if (typeof(WebForm_RestoreScrollPosition) == 'function') {" + "\n" +
"WebForm_RestoreScrollPosition();" + "\n" +
"}" + "\n" +
"var destination = $('#" + lblMessage.ClientID + "').offset().top;" + "\n" +
"$('html, body').animate({ scrollTop: destinatio开发者_运维技巧n-20}, 500 );" + "\n" +
"});" +
"</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "scrollToMessage", script);
// ### END SOLUTION ###
Thanks!
Set MaintainScrollPositionOnPostback="false"
in Page directive in your page to disable the default page scrolling on post back. Then your code should scroll the page as per the logic.
Simply had to call manually ASP.NET's WebForm_RestoreScrollPosition(). Clean result.
String script = "<script type=\"text/javascript\">" + "\n" +
"$(document).ready(function() {" + "\n" +
"if (typeof(WebForm_RestoreScrollPosition) == 'function') {" + "\n" +
"WebForm_RestoreScrollPosition();" + "\n" +
"}" + "\n" +
"var destination = $('#" + lblMessage.ClientID + "').offset().top;" + "\n" +
"$('html, body').animate({ scrollTop: destination-20}, 500 );" + "\n" +
"});" +
"</script>";
ClientScript.RegisterClientScriptBlock(this.GetType(), "scrollToMessage", script);
精彩评论