If you have a multi-level, expandable list of items to display on your site (e.g. a product category hierarchy with drilldown capability - see image below), the asp.net treeview server control can be just the right tool for this user experience.
Unfortunately, an irritating drawback of the treeview is that each time the user selects an item, the treeview control forces a postback to the server and the web browser’s position will reset back to the top of the screen. This is not a great experience if the user must continually scroll down after each click to see the next level in the category hierarchy. In fact they may not even realize there are more items to choose from in the browser.
A solution I found to overcome the issue was to move the browser’s scroll position to the selected item by leveraging the postback that automatically occurs on the treeview click event.
i.e. on the postback, grab the selected categoryid and name and send it back to the client for use in jQuery. Script can then find the categoryid/categoryname in the browser and automatically scroll the browser to selected node in the treeview via the scrollTop method.
Steps:
In the code behind (below) we determine the user’s selected item in the TreeNodeExpanded click event, and then write that back to the client via a literal server control on the page.
Code Behind:
protected void tvCategories_TreeNodeExpanded(object sender, TreeNodeEventArgs e)
{
CategoryName = e.Node.Text;
CategoryID = Convert.ToInt32(e.Node.Value);
SetCategoryValues();
}
private void SetCategoryValues()
{
string script =
"";
ActiveNodeScripts.Text = script;
}
Page Markup:
Inside your .js file or in the page markup, declare the var 'ScrollThis' via:
$(document).ready(function() {
if (jQuery.browser.safari) // apple browsers
{
ScrollThis = jQuery("body");
}
else
{
ScrollThis = jQuery("html"); // android or any other browser that’s not safari
}
});
Conclusion
By leveraging the steps in this article, you can provide a cookieless approach to maintaining the scroll position details of ASP.NET treeview server control. This should easily overcome the shortcoming of the Treeview’s postback and provide the proper user experience for your site.
Thanks to Aris Labros for the jQuery assistance, and be sure to check out what he's got to say on his blog.