Showing posts with label postback. Show all posts
Showing posts with label postback. Show all posts

Sunday, April 13, 2008

ASP.NET retain scroll position on Post back

This post is about retaining the scroll position on the ASP.NET page on Post Back. There are few ASP.NET in built features like smartNavigation ,MaintainScrollPosition (2.0 and above) available. But these features have its own drawbacks like tampering the View State, improper page redirects, breaking the css links etc. Here is an approach to retain scroll position in ASP.NET page.

Include a hidden variable in the web page: The hidden variable is added to the web page to save the current position of the window. The hidden variable can be included inside the form tag.



Capture the current scroll position: The javascript injected on the HTML captures the current scroll position. The following document events trigger the function call which will capture the current position.

window.onscroll = saveScroll;
window.onresize = saveScroll;

The script above will trigger the saveScroll method when the window is scrolled or resized. The current position is saved in the hidden variable in the saveScroll method. The definition of saveScroll function is as follows.

function saveScroll()
{
var sScroll;
if (document.documentElement && document.documentElement.scrollTop)
sScroll = document.documentElement.scrollTop;
else if (document.body)
sScroll = document.body.scrollTop;
else
{
sScroll = 0;
}
document.getElementById('__SAVESCROLL').value = sScroll;
}
Restore The Scroll: The scroll position has to be restored when the page post back happens. The following document event triggers the function call which will restore the scroll position.
window.onload = restoreScroll;
The window.onload event will fire after the web page finishes loading. Once the web page finishes loading, the hidden variable where we save the previous scroll position will be available get and restore the scroll back to the same location. The definition of restoreScroll method is given below.

function restoreScroll()
{
var sScroll = document.getElementById('__SAVESCROLL').value;
if (sScroll > 0)
{
if (document.documentElement)
document.documentElement.scrollTop = sScroll;
else if (document.body)
{
if (window.navigator.appName == 'Netscape')
window.scroll(0, sScroll);
else
document.body.scrollTop = sScroll;
}
else
{
window.scroll(0, sScroll);
}
}
}