Some days ago I had come across with an issue regarding browser scroll position. Although the problem was a little trickier as the page was
including some JQuery expanders as well, but for now I’m just going to tell you how I managed to solve this problem.
As an ASP.NET programmer, I had a some very nice straight options:
- I can use maintainScrollPositionOnPostBack="true" in web.config pages section to maintain scroll position for all pages.
- I can use MaintainScrollPositionOnPostback="true" in page declaration for some specific page.
- Programmatically set System.Web.UI.Page.MaintainScrollPositionOnPostBack = true;
But I prefer to write this post for JQuery to make it available for other web technologies as well. So let’s start then :).
The solution can be broken down into two simple tasks:
- Save scroll position whenever user scrolls the page in a container like cookies.
- Set the scroll position when page is loaded again by reading the same container.
We can determine the user scroll action by simply registering the scroll event of the javascript window object when document ready event is fired i.e.
$(document).ready(function(){
$(window).scroll(SaveScrollPosition);
});
Here is the definition for SaveScrollPosition function:
function SaveScrollPosition()
{
var target = 'scrollTop';
var container = $(window);
$.cookie(target, container.scrollTop, { expires: 2 });
}
Here I’m planning to maintain only the vertical scroll position that’s why I’ve stored only scrollTop property of the container. For cookie management I’ve used the JQuery cookie plug-in written by Klaus Hartl.
Now let’s come to the second task of setting the scroll position upon page load. We can use the same document ready event written earlier for this task as follows:
$(document).ready(function(){
$(window).scroll(SaveScrollPosition);
var target = 'scrollTop';
var container = $(window);
if(typeof $.cookie(target) != 'undefined')
container.scrollTop = $.cookie(target);
});
I’ve used the same cookie name 'scrollTop' as used in SaveScrollPosition to retrieve cookie value and have set the scrollTop property of the container with this value.
Simple! Isn’t it???
Blogger Labels: Web,ASP.NET,Scroll,Cookies,JQuery
