Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET
Article

How to scroll an ASP.NET control into view after page load using codebehind

Rate me:
Please Sign up or sign in to vote.
4.67/5 (29 votes)
21 Mar 2005 157.1K   51   18
This simple function uses JavaScript to scroll any control into view after the page has loaded.

Introduction

In some cases when an ASP.NET page loads the control, you need to focus on is not visible because it is further down the page. I have had numerous occasions when a request variable indicates which item on a long list the user is interested in viewing, this script can help by scrolling the particular item into view.

Code

The following function I have added to a Utils.dll library for general use so is static and needs the current page as a variable.

C#
public class Utils
{
   public static void FocusControlOnPageLoad(string ClientID, 
                                       System.Web.UI.Page page)

   {

      page.RegisterClientScriptBlock("CtrlFocus",

      @"<script> 

      function ScrollView()

      {
         var el = document.getElementById('"+ClientID+@"')
         if (el != null)
         {        
            el.scrollIntoView();
            el.focus();
         }
      }

      window.onload = ScrollView;

      </script>");

   }
}

You can use this as follows:

C#
private void Page_Load(object sender, System.EventArgs e)
{
Utils.FocusControlOnPageLoad(this.yourcontrol.ClientID, this.Page);
}

Hopes this helps someone.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Founder Tech Dept
United Kingdom United Kingdom
My Evolution:
TRS-80 Basic, Clipper, C, Better Basic, FORTRAN, C++, Visual Basic, Delphi, C#

Comments and Discussions

 
GeneralSlightly different scenario Pin
Mihai Drebot12-Apr-08 6:14
Mihai Drebot12-Apr-08 6:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.