Reader Level:
ARTICLE

Use JavaScript method scrollIntoView in ASP.NET

Posted by Manish Dwivedi Articles | ASP.NET Programming December 13, 2010
In this article I am trying to explain for you how to use the JavaScript method scrollIntoView in ASP.Net.
  • 0
  • 0
  • 8770

As you know it is very easy to scroll a page in ASP.Net, by defining an anchor tag you can do this but in this article I am going to explain for you how to a scroll page from server side with the help of JavaScript method scrollIntoView.

For that you have to write JavaScript like the following in code behind. Here I have defined one method in code behind.
 

 

public void ScrollToMyFavouriteControl(System.Web.UI.Control ctrl)

{

    System.Text.StringBuilder script = new System.Text.StringBuilder();

    string clientID = ctrl.ClientID;

 

    script.Append("<script type='text/javascript'>");

    script.Append("try {");

    script.Append("document.getElementById('" + clientID + "').scrollIntoView(true);");

    script.Append("document.getElementById('" + clientID + "').focus();");

    script.Append("} catch (e) {}");

    script.Append("</script>");

    RegisterStartupScript("setScrollAndFocus", script.ToString());

}


In the above method I have registered the script for setting the Scroll and Focus.

After that I have called the defined method in the Page Load like that.

 

if (!Page.IsStartupScriptRegistered("setScrollAndFocus"))

{

    ScrollToMyFavouriteControl(TextBoxMyFavourite);

}



Since I got one comment for this article, Yes it is true that RegisterStartupScript is obsolete in higher .Net framework versions, so what is the alternative.

You can replace RegisterStartupScript with ClientScript.RegisterStartupScript like this.


 

public void ScrollToMyFavouriteControl(System.Web.UI.Control ctrl)

{

    System.Text.StringBuilder script = new System.Text.StringBuilder();

    string clientID = ctrl.ClientID;

 

    script.Append("<script type='text/javascript'>");

    script.Append("try {");

    script.Append("document.getElementById('" + clientID + "').scrollIntoView(true);");

    script.Append("document.getElementById('" + clientID + "').focus();");

    script.Append("} catch (e) {}");

    script.Append("</script>");

    Page.ClientScript.RegisterStartupScript(this.GetType(),"setScrollAndFocus", script.ToString());

}


and in the Page Load now we will check like below:

 

if (!ClientScript.IsStartupScriptRegistered("setScrollAndFocus"))

{

    ScrollToMyFavouriteControl(TextBoxMyFavourite);

}



Here TextBoxMyFavourite  is the id, to which I want to set Focus and Scroll.

This example works on (IE, FireFox and Chrome).





COMMENT USING

Trending up