Click here to Skip to main content
Click here to Skip to main content

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

By , 21 Mar 2005
 

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.

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:

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

About the Author

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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberlighthousekeeper5 Apr '13 - 11:05 
works great - thanks!
GeneralThanks!!memberxanderex17 Aug '10 - 13:26 
Thank you !!
i did not use your code but the function scrollIntoView() was really hard to find it.
thank u for posting it XD
GeneralUsing in a Modal PopupmemberNate_115 Sep '09 - 10:32 
I have a Modal Popup setup where I would really like to use this script, though when focus is set, which also happens if using #Anchor, the entire Frame inside the Popup is moved up, this creates problems as the Modal popups Navigation is at the top of the page and is hidden from sight.
 
e.g
 
/*This Disappears if the script is run*/
<asp:button id="btnNext" />
etc...

Body
etc...
Something way down the page to Focus
 
Is there a way around this problem, the top of form Navigation is important.
GeneralSlightly different scenariomemberMihai Drebot12 Apr '08 - 6:14 
I needed to scroll to a specific position in the page when a button was pressed (ie. when i select a row for editing in a gridview, i want to scroll to the formview that does the actual editing)
So here is how i did it:
 
added in PageLoad
Page.RegisterClientScriptBlock("CtrlFocus",
@"<script>
function ScrollView(ClientId)
{
var el = document.getElementById(ClientId)
if (el != null)
{
el.scrollIntoView();
el.focus();
}
}
</script>");

 
added to the button properties
OnClientClick="javascript:ScrollView('editAnchor')"
 
and finaly added an anchor just before the formview:
OnClientClick="javascript:ScrollView('editAnchor')"
 
for this to work with the postback, i had to also set the MaintainScrollPositionOnPostback="true" of the page.
 
I hope this helps
GeneralHorizontal Scrollmembersree473 Aug '05 - 16:29 
Thanks so much. This just works great! But I could only get vertical scroll bar with this code. How do I get horizontal scroll bar? I'm sure this is a simple manipulation of the code, but if you could show a sample piece of code that does this, it would be great!
 
Thanks,

 
Sree.
GeneralI had trouble with the window.onloadmembertanr16 Mar '05 - 16:53 
This line does not work for me, it appears to be a csharp'ism that snuck into javascript code.
 
"window.onload += ScrollView;"
 
changed it to
"window.onload = ScrollView;"
 
Things worked a lot better for me then.

GeneralRe: I had trouble with the window.onloadmemberAch1lles21 Mar '05 - 0:07 
Thanks for spotting that. Have changed the code.
GeneralThis is only MSIE specificmemberstp7 Mar '05 - 23:16 
Hello,
 
you should use document.getElementById instead of document.all, because document.all does not exist in the official javascript standard. It is only implemented in >= MSIE4.0. With these browsers, it works fine in javascript-blocks too, but exactly it's a JScript command.
 
document.getElementById is the official supported method by DOM. All Browser I know, supports this.
 
Best regards
Stephan
GeneralRe: This is only MSIE specificmemberAch1lles8 Mar '05 - 0:02 
Good point.
 
Have updated the code to use this. Thanks
 
Richard
GeneralActually - nomemberleopfeifenberger3 Mar '05 - 2:52 
because
 
-- only IE supports this
-- that's exactly the same thing what ASP.NET does after a PostBack when you activate "SmartNavigation" (among other things)
GeneralRe: Actually - nomemberAch1lles3 Mar '05 - 3:14 
Sorry I should have stated this was actually IE and Firefox specific code. I find most people use one of these two.
 
I do realise that smart navigation will do this for a postback, this is for use in an initial page request situation where a request variable defines the point of focus on a page.
 
Regards
 
Richard
GeneralRe: Actually - nomemberleopfeifenberger3 Mar '05 - 3:32 
I experimented with .scrollIntoView() a while ago and found it (while being simple to use) a bit sloppy;
 
I had a JS-TreeView which had to reposition itself when a Node was opened. The .scrollIntoView() worked perfectly, but the scrollPosition was 2 pixels off - not much, but the offset was added at every click, so afer 4 clicks, the focus was 8 pixels off.
 
Now we calculate the exact X-Position of the anchor, and use window.scrollBy(x,y) to bring teh desired control into focus.
 
cheers,
 
Leo
GeneralRe: Actually - nomemberAch1lles3 Mar '05 - 3:48 
Thanks Leo, thats useful to know. I will look into updating this sometime.
 
Regards
 
Richard
GeneralRe: Actually - nomemberAshaman21 Mar '05 - 5:06 
leopfeifenberger wrote:
Now we calculate the exact X-Position of the anchor,
 
I'd love to see an example of this.
GeneralRe: Actually - nomemberlp34421 Mar '05 - 20:53 
Hi Ashaman (<-- Good to see SOMEBODY is still reading Robert Jordan Poke tongue | ;-P )
 
it's something like this:
<SCRIPT LANGUAGE=javascript>
<!--
/*
getElementPos(ElementName)
 
info: Gets the Coordinates of an Element. 
Can be any ObjectId (of DIVs, Anchors ect.)
 
params: Id of Emelent to get Coords
return: Coord Object
 
*/
function getElementPos(pElmName)
{
	//	find "Destination" Element
	var elm = findObj(pElmName);
	var coords = {x: 0, y: 0 };
	
	// Tricky: Recursive Function to get 
        // Coords of Destination Element 
        // + sum of Coords of "parent" Elements:
	// background: offsetLeft/offsetTop only 
        //gets the Offset to the Parent Object...
	while (elm)
	{
		coords.x += elm.offsetLeft;
		coords.y += elm.offsetTop;
		elm = elm.offsetParent;
	}
	return coords;
}
 
/*
ScrollToElement(ElementName)
 
info: Scrolls to Element. 
Can be any ObjectId (of DIVs, Anchors ect.)
 
params: Id of Emelent to Scroll To
return: void
 
*/
function scrollToElement(pElmName)
{
	// Get the Position of the Element
	var pos = getElementPos(pElmName);
	// Just a hardcoded fix, 
        //is written by the COntrol based 
        //on ChildControls
	if (pos.y>200) pos.y -= 20;
	
	// Finally --> scroll into Position
	window.scrollTo(pos.x,pos.y);
}
 
// MM DreamWeaver findObj() Function
function findObj(theObj, theDoc)
{
  var p, i, foundObj;
  
  if(!theDoc) theDoc = document;
  if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
  {
    theDoc = parent.frames[theObj.substring(p+1)].document;
    theObj = theObj.substring(0,p);
  }
  if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
  for (i=0; !foundObj && i < theDoc.forms.length; i++) 
    foundObj = theDoc.forms[i][theObj];
  for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) 
    foundObj = findObj(theObj,theDoc.layers[i].document);
  if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
  
  return foundObj;
}
 
//-->
</SCRIPT>
 
I just wrote this from the top of my head (where is the Sysntax highlighting in this textbox ;PP ), 
obviousely not tested, so there might be some syntax errors. 
 
But it shoud be enough to get you on the right track.
 
Greets
 
Leo 

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 21 Mar 2005
Article Copyright 2005 by Ach1lles
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid