Maintain Scroll Position of DIV using JavaScript - ASP.NET 2.0

Some people have some problems in maintaining the position of the DIV. Initially, The most of people are using htc for solving this problem. but there are so many disadvantages of using htc such as it works only in Internet Explorer, it doesn’t work properly with Visual Studio 2005 and so on.

Finally, I got the solution for solving this problem.. Using Javascript for keeping the scroll position is the best way to go.. JavaScript helps us to know the current position of DIV. Plus, we can use HTTP Cookie for storing the value of the previous position of DIV tag.

SouceCode Download : http://michaelsync.net/demo/MaintainScroll.zip


window.onload = function(){
var strCook = document.cookie;
if(strCook.indexOf("!~")!=0){
var intS = strCook.indexOf("!~");
var intE = strCook.indexOf("~!");
var strPos = strCook.substring(intS+2,intE);
document.getElementById("grdWithScroll").scrollTop = strPos;
}
}
function SetDivPosition(){
var intY = document.getElementById("grdWithScroll").scrollTop;
document.title = intY;
document.cookie = "yPos=!~" + intY + "~!";
}

I have tested this code with IE6, 7 and Mozilla Firefox. It’s working very fine.
Please let me know if you have any problem with this coding. Thank you.
Special Thanks to Jim Ross and Eric Pascarello.

UPDATED Maintain Scroll Position of DIV using ASP.NET Ajax by Brad Alcock (Thanks for sending this mail, Brad.)

hi. here’s the code with a very brief explanation on what goes on behind the scenes.

a little different to what you did, but sort of on the same track. I’m sure you can find a method of working around it to fit in with your post ^^

right, my div’s id was panel1, I basically created a cookie for the onscroll of the div in the function SetDivPosition(). the read cookie is read using the stringbuilder in the C# Page_load code underneath.


function SetDivPosition(){
var intY = document.getElementById("Panel1").scrollTop;
var date = new Date();
date.setTime(date.getTime()+(1*60*60*1000));
var expires = "; expires="+date.toGMTString();
document.cookie = "cookie1"+"="+intY+expires+"; path=/";
document.title = intY;
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

here is the string builder in the page Load. the part in the if(!IsPostback) is there so that when the page is loaded for the very first time, it removes any possibility of a cookie being there (incase the page is returned to within an hour. ) that means the scrollbar will not suddenly jump to a position at arb times like first time page is loaded.
don’t forget to use System.Text; otherwise it will throw an error.


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
StringBuilder sbScript = new StringBuilder();
sbScript.Append("<script language='JavaScript' type='text/javascript'>");
sbScript.Append("document.cookie = cookie1 + \"=\" + \"\" + -1 + \"; path=/\";");

sbScript.Append("</script>");
// Make use ScriptManager to register the script
ScriptManager.RegisterStartupScript(this, this.GetType(), "@@@@MyCallBackAlertScript", sbScript.ToString(), false);

}
StringBuilder sbScript1 = new StringBuilder();
sbScript1.Append("<script language='JavaScript' type='text/javascript'>");
sbScript1.Append("var strCook = readCookie(\"cookie1\"); "+
"document.getElementById(\"Panel1\").scrollTop = strCook;");
sbScript1.Append("</script>");

// Make use ScriptManager to register the script
ScriptManager.RegisterStartupScript(this, this.GetType(), "@@@@MyCallBackAlertScript", sbScript1.ToString(), false);
}

Regards,
Brad

/*References
*
* Maintain Scroll Position in any Page Element
* http://authors.aspalliance.com/jimross/Articles/MaintainScrollPos.aspx
*
* Remember a Div’s Scroll Position
* http://radio.javaranch.com/pascarello/2005/07/18/1121709316718.html
*/

[digg=http://digg.com/programming/Maintain_Scroll_Position_of_DIV_using_JavaScript_ASP_NET_2_0/]

105 Comments so far »

  1. ria said

    am November 5 2006 @ 12:57 pm

    thank you very much.
    is it possible to show the headerrouw permanently in the scrollarea?

  2. Michael Sync said

    am November 6 2006 @ 2:09 am

    head arrow?
    I guess, you may use a style which is set mouse pointer to “hand” or “pointer”..

  3. Erik said

    am November 7 2006 @ 7:17 pm

    Kudos and thanks for the code. Short and sweet. I prefer this to the other, overly complicated solutions I have seen so far.

  4. ASP.NET Forums - Maintain scroll position of a DIV over a callback said

    am January 26 2007 @ 4:58 pm

    [...] my UpdatePanel has done it’s callback thang.  I found the best looking method using cookies Here  but, as said above, i can’t get the onload function to fire when a callback completes.  [...]

  5. Jerold said

    am January 29 2007 @ 7:02 am

    You know this solution works okay with records or lines in the scrollable div at 300 to 500 or less, but lines over 500 and your method to maintain scroll position doesn’t work. If you have a work around, I would love it.

  6. Michael Sync said

    am January 29 2007 @ 7:49 am

    Hi Jerold,

    >>lines over 500 and your method to maintain scroll position doesn’t work

    I have tested with 1000 lines. [Firefox2, IE7 ] It’s working fine.

    Could you please tell me the steps to reproduce the issue? or maybe. it would be great if you can send me the sample project that give ur error.

    I will take a look and will let you know as soon as possible.

    you can find my email address in “About Me” page. ** Please put this “[Michael Sync's Blog]” in Subject when you are sending a mail to me.

    Thanks a lot for visiting my blog.

  7. Mahdi said

    am February 14 2007 @ 12:14 pm

    Hi Michael
    I have a problem with asp.net 2.0 and javascript. I want to send Scroll Position of a DIV to the server side code. In fact i need to send a variable which is claculated in javascript to my server side asp.net 2.0 code. But there is some problem. I cant add the variable value to a hidden or any html control like that. Also I tryed to send it to server using KVP (key vlaue pair) and http get but the trick dont work.
    I am thankfull if you can help me.
    Best Regards.

  8. Michael Sync said

    am February 15 2007 @ 3:10 am

    Hi Mahdi,

    >>I cant add the variable value to a hidden or any html control like that.

    Why? because you wanna pass KVP to Server-side code?

    it can be done by using Hidden Field Server Ctl.. then, you can add KVP as an JSON Javascript object to this hidden Field.

  9. Michael Sync said

    am February 15 2007 @ 3:58 am

    There is another way to achieve this goal.. you may use cookie in your page.
    Cookie can be accessed from both Client-side script and Server-side script.
    Here is an example.
    Using Cookie (C# + Javascript)

  10. Mahdi said

    am February 19 2007 @ 10:24 am

    Thanks for your help. It was great.

  11. Michael Sync said

    am February 19 2007 @ 10:27 am

    Your welcome. Mahdi. Thanks for visiting my blog.

  12. selva said

    am March 15 2007 @ 7:18 am

    thank you very much.
    is it posible that use any other event instead of window.onload?
    I am using AJAX and page does not fire the onload event is there any other way I can make this function work for my application.

  13. Michael Sync said

    am March 15 2007 @ 7:33 am

    you may put the codes which are written in window.onload event to one function (let’s say “function myfunc() {};”).

    eg:

    function myfunc(){
    var strCook = document.cookie;
    if(strCook.indexOf(”!~”)!=0){
    var intS = strCook.indexOf(”!~”);
    var intE = strCook.indexOf(”~!”);
    var strPos = strCook.substring(intS+2,intE);
    document.getElementById(”grdWithScroll”).scrollTop = strPos;
    }
    }

    then, you can invoke this function at anytime you want.

    Note: The main need of this function is that to keep the scroll position of something (eg: GridView) after Page PostBack.

    If the page doesn’t have “Postback” then this function won’t be required for you..

  14. selva said

    am March 15 2007 @ 10:29 am

    Thank you for the help and quick reply !!

    Cheers
    -Selva

  15. jackxsks said

    am April 18 2007 @ 2:33 pm

    If you have to do it, you might as well do it right

  16. Michael Sync said

    am April 19 2007 @ 3:03 am

    >>If you have to do it, you might as well do it right

    :-0 what do u mean?

  17. Veronika said

    am April 25 2007 @ 1:06 pm

    My name is Veronika.
    I saw your blog and I found cognitive.
    So, what do you think about our collaboration?
    I believe it would be great to exchange blogs!
    My blog is: http://cigarettestyle.blogsome.com
    Wait for your reply.
    Have a nice day.
    Veronika.

  18. dvh said

    am May 2 2007 @ 7:40 am

    great script!
    one thing though, onscroll my window title gets set to the line number.

    any ideas?

  19. Michael Sync said

    am May 2 2007 @ 7:59 am

    Hi dvh,

    you mean, you dont wanna show line number in window title???
    you may remove this line..

    document.title = intY;

    Hope it helps..

  20. dvh said

    am May 2 2007 @ 8:04 am

    nevermind : document.title = intY;

    :^)

  21. David Anderson said

    am May 8 2007 @ 2:26 pm

    I am unclear about how to use this when an AJAX UpdatePanel is involved. Can you provide some specific instructions or a sample for someone who is an AJAX neophyte?

  22. Michael Sync said

    am May 9 2007 @ 8:18 am

    Hi David,

    Sorry for late reply..

    The main thing is that how you use UpdatePanel in your page. Generally, it wont need to control the position of scrollbar if you are using UpdatePanel.

    It’s better if you show me how you used UpdatePanel in your page. maybe. send me a sample of your page. I will take a look and will get back to you.

    As I said in this post, I’m very busy with moving out of my country and seeking new job.. i think, i can reply the details after setting-up with my thing…

    Thanks..

  23. David Anderson said

    am May 9 2007 @ 12:06 pm

    Here’s the complete code for the UpdatePanel. The scroll position is not maintained after the Select button is clicked. I know you are busy but I thank you for your help!

  24. David Anderson said

    am May 9 2007 @ 12:07 pm

    Well, darn, it looks like the code got stripped out. How can I get it to you?

  25. Michael Sync said

    am May 11 2007 @ 2:55 am

    ya. you can reach me with this addr (mchlsync AT gmail.com) thanks

  26. suyog kale said

    am June 6 2007 @ 12:33 pm

    give me some more examples

  27. suyog kale said

    am June 6 2007 @ 12:34 pm

    give me some more examples with DIV

  28. Michael Sync said

    am June 7 2007 @ 4:52 pm

    u want more example? please more specific..

  29. Andrew said

    am June 25 2007 @ 9:29 pm

    Hello. Thank you for the great post. I am trying to maintain the scroll position on the horizontal scroll bar. Is this possible? If so, how would your code be modified? Many thanks!

  30. Michael Sync said

    am June 27 2007 @ 10:27 am

    Sorry. I was not able to surf internet for a while.. sorry for late reply…

    for your problem ~
    Try with scrollLeft instead of scrollTop…

    Hope, it would help..let me know if scrollleft doesn;t work for you..

    Thanks for visiting my blog. :)

  31. Mike OShields said

    am June 29 2007 @ 3:06 pm

    Code works great. Thanks. Question: How can I modify the code to be able to handle multiple div’s on a single page?

    Thanks again

  32. Chad said

    am July 5 2007 @ 6:34 am

    I can’t seem to get this script to function properly inside of an updatepanel. If you change the window.onload trigger, where would be the best place to call the function from? Do you have to store the script inside the updatepanel for it to work?

    window.onload = function(){
    var strCook = document.cookie;
    if(strCook.indexOf(”!~”)!=0){
    var intS = strCook.indexOf(”!~”);
    var intE = strCook.indexOf(”~!”);
    var strPos = strCook.substring(intS+2,intE);
    document.getElementById(”div-gridview”).scrollTop = strPos;
    }
    }

    function SetDivPosition(){
    var intY = document.getElementById(”div-gridview”).scrollTop;

    document.cookie = “yPos=!~” + intY + “~!”;
    }

  33. Michael Sync said

    am July 5 2007 @ 11:40 am

    I have tried with ASP.NET AJAX.
    i think it might be cuz of ur DIV id might be changed at runtime. You should check the ViewSource what actual id is at runtime..

  34. nanu said

    am July 11 2007 @ 9:41 am

    How to maintain the position of horizontal as well as vertical scrollbar position

  35. Michael Sync said

    am July 11 2007 @ 10:03 am

    Just take care of scrollLeft and scrollTop in code. it will work.

  36. Alee said

    am July 23 2007 @ 8:06 pm

    Somehow, when I use this code, the cookie never gets created. The browser is able to create cookies from other sites

  37. Ashraf said

    am July 30 2007 @ 8:13 am

    Wonderful solution. The best I have seen so far. Simple, short and straight to the point. Thanks Michael..

  38. nicky said

    am July 31 2007 @ 11:38 am

    Hi. Nice solution but it doesn’t work out for me at this time :(
    The div wich scroll position I would like to maintain has the runat=server tag. When I find this control ( var div = document.getElementById(”); ) div.scrollTop allways returns 0. Any idee why?

    I found another post with a simular problem. Only difference is that i do not use a masterpage: http://www.velocityreviews.com/forums/t293566-master-pages-and-scrolltop-0.html

    thx for your help, cheers

  39. Michael Sync said

    am July 31 2007 @ 11:54 am

    there are three ways to solve your problem.

    1. Find the actual client id of server-side DIV in View Source. And put this in javascript. (note that the client id might be changed for some reasons from one time to another.)

    2. Register this script from server-side (code-behinded file) with DIV.ClientID

    3. Give the static id in Form load . eg: this.ID = “MyPageID”. then. call the name of DIV with that id you just give. .eg: document.getElementByID(’MyPageID_DIV1′);

    Hope, it would helps.

  40. nicky said

    am July 31 2007 @ 12:04 pm

    thx for your quick reply!!

    Okay, I see some of my code disapered after posting. I find the div by using the followin code without spaces:

    var div = document.getElementById( ‘ ‘)

    and that wil result in the following runtime code:

    var div = document.getElementById(’CockpitPageControlManager_taskPane_objectListViewOpenTasks_grdWithScroll’);

    then, I find the div but scrolltop always returns 0

  41. nicky said

    am July 31 2007 @ 12:04 pm

    hmmz, it seems the code get’s stripped, hope you see what I mean now ~~

  42. Michael Sync said

    am July 31 2007 @ 3:34 pm

    it’s strange . Can you please create a small sample project and send it to me? I will look what I can do for that issue.

    for the time being, I’m checking the link that you gave me..

  43. Michael Sync said

    am July 31 2007 @ 4:25 pm

    which version of ASP.NET are you using? 2.0?

  44. Michael Sync said

    am July 31 2007 @ 4:41 pm

    Its working. I have tried with the following sample ~

    In HTML view

     <input id=”Button1″ type=”button” value=”button” onclick=”foo();” />
    <div style=”overflow:scroll; height:300px;” id=”mydiv” runat=”server”>
       <div
    style=” background-color:Red; height:800px;” >
          <div style=”height:300px; background-color:Green;”>

         </div>

        </div>
    </div>

    In Page_Load

    if (!ClientScript.IsClientScriptBlockRegistered(”myscript”))
    {

    System.Text.StringBuilder sBdr = new System.Text.StringBuilder();
    sBdr.Append(”");
    sBdr.Append(” function foo(){”);
    sBdr.Append(” alert(document.getElementById(’” + mydiv.ClientID + “‘).scrollTop);”);
    sBdr.Append(” }”);
    sBdr.Append(”");
    ClientScript.RegisterClientScriptBlock(typeof(Page),”myscript”, sBdr.ToString());
    }

    You will get the scrollTop as 0 if you don’t move the scrollbar position of the server-side DIV called “mydiv”. You just scroll down a lit bit. then, You will get something different for scrollTop .

    So, this issue is not replicated in my site. I assume that you are getting 0 because the div that you mention doesn’t have the vertical scroll bar or you haven’t moved any movement to that scroll bar..

    Please test it again.. let me know the result.. If you are still facing the problem, send the sample to me. I will take a look and try to help you as much as I can.

  45. nicky said

    am July 31 2007 @ 10:13 pm

    thx again for your quick reply. I’ve send you an email with a sample project. I’m using asp.net 2.0 with ajax.asp.net 1.0. Pay atention to the doctype (i’m not using one :o)

    hope you can tell me why it isn’t working.

    Cheers,
    Nicky

  46. Michael Sync said

    am August 1 2007 @ 7:42 am

    I know the reason why it’s not working.

    reason 1. The div id that you have passed to the function is the last div id. So, the first and second div panel wont’ work.

    reason 2. there are so many same js function name. (because you put those js in web user control and you have added more than one web user control in your page. So, there will be a lot of SetDivPosition and GetDivPosition functions in one page.)

    I have updated your sample and send it back to you. Please check the attachment.

    [Source Code Download : http://www.esnips.com/doc/94adcf11-b3fa-47cc-bb0e-8a674cb18c5f/ScrollDivTest—Updated/

    It works for each DIV. eg: If you click the button from DIV1, the position of DIV1 will be kept but not for DIV2 and DIV3.

    but you will get the actual scrolltop value of each DIV instead of 0.

    I will test for improvement.. but im at work now so i can’t test much..

  47. nicky said

    am August 1 2007 @ 8:03 am

    Hi Michael,

    To cool!! It’s working now. No further testing required, it’s working great!! Really thx for your quick and usefull replies!! I bookmarked your blog for future solutions ;)
    thx again!

    Cheers,
    Nicky

  48. Jumana Mhowwala said

    am August 13 2007 @ 12:12 pm

    Hi,

    i tried to implement solution suggested by you.
    .

    But it says onscroll not a valid attribute of div.
    i m using asp.net 2.0.

  49. Michael Sync said

    am August 15 2007 @ 2:10 pm

    yeah. VS says like that. but it is okay. you can still use this attribute and it works..

    Check-out the link below. u will see all properties, methods, events (including onscroll) of DIV object..

    div Object (MSDN)

  50. Dana said

    am August 23 2007 @ 10:09 am

    Hello,

    I am trying to use your code in a AJAX asp.net application i have written.
    I am using an updatePanel with a timer which reloads the grid every 4 seconds.
    In Page_Load event I added (becuase the window onload event isn’t invoked in every refresh):

    ClientScript.RegisterStartupScript(this.GetType(), “SetScroll”,”SetScroll()”);

    But the function isn’t called every refresh.
    Can you please help?

    Thank you very much,
    Dana

  51. Pooja said

    am August 30 2007 @ 8:12 am

    Hello
    I want to scrool images from database
    can u help me to do so..
    i want to do it in asp
    i tried alot, but all in vain
    plz help me!!!
    thanks
    Pooja

  52. ashish ambokar said

    am September 2 2007 @ 1:02 am

    hey Michel
    Thank you very muxh for such a nice post.
    it working absolutely fine.
    people like u make our job easy.
    thanks again

  53. Pradeep said

    am September 12 2007 @ 8:13 pm

    Thanks for the script. I ran into a similar reqiurement and was thinking of the same cookie solution. You script saved my time.

  54. Amaan Kazi said

    am October 3 2007 @ 11:12 am

    I am trying to use your code in a AJAX Update panel

    But the function you suggested dosent work kinly suggest

    Thanks,

    Amaan Kazi

  55. John said

    am October 5 2007 @ 2:03 pm

    ClientScript.RegisterStartupScript is not your best bet.. since this is AJAX, you probably have a ScriptManager control on page… so something like this might work..

    ScriptManager.RegisterStartupScript(this, this.GetType(), “SetScroll”,”SetScroll()”, false);

  56. Fred N said

    am October 24 2007 @ 7:35 am

    Hi Michael

    In the same idea of keeping the scroolbar on a GridView (or DataGrid in ASP 1.1) i mixed your code with another who
    keep the header on top :

    window.onload = function()
    {
    var t = document.getElementById(”");
    var t2 = t.cloneNode(true);
    for(i = t2.rows.length -1;i > 0;i–)
    t2.deleteRow(i);
    t.deleteRow(0);
    gridheader.appendChild(t2);

    var grdWithScroll = document.getElementById(”grdWithScroll”);
    grdWithScroll.scrollTop = * t.cells[1].clientHeight;
    }

    Hope this help someone…

    Fred.

  57. magesh said

    am October 30 2007 @ 3:47 am

    can you explain me the scrollbar maintanance after selecting the radio button in the page event.i am using 1.1 version.

  58. Michael Sync said

    am October 30 2007 @ 4:36 am

    then, you need to tell me more about what you wanna do…… basically, my code keep the scroll position when the page got refreshed……. so, no matter whether radio button or not.. it will keep the scroll position ……

  59. Sydney said

    am October 30 2007 @ 9:18 pm

    My html tags in my original message seems to be all gone.

  60. Najeeb Ahmed.G said

    am October 31 2007 @ 3:02 am

    Sir,

    I am doing my project in asp.net.In my project i would like to add the scroll image. So kindly send me the script as soon as possible

    Regards
    Najeeb

  61. Michael Sync said

    am October 31 2007 @ 3:45 am

    Hi Najeeb,

    All you need to do is that just your IMG tag within DIV. And, specify the width and overflow:auto in CSS and set this CSS to this DIV .. That;s all you need..

    eg: #divTest{width:150px;height:200px;overflow:auto}

    Hope it helps..

  62. Sydney said

    am October 31 2007 @ 5:52 am

    Not sure what happened to my original post. Here it is again. I’ve beeb testing this for half a day to get IE working.

    I used your original code with a divTest and many 1\ inside the div. I changed all the 1 to a link that reloads the html itself. When I scroll, the title does indicate the scrollbar position. If I scroll to let’s say 198 and then click the link beside the scrollbar, the page reloads, but the title changes to Fun Scroll, and then scrolls to 42 which is now indicated in the title. i.e. the title flashes from Fun Scroll to 42. No mater which line I tried, after reload the scroll bar always comes back to 42. I pasted my code yesterday but the site strips out all the html tags. The difference between your code and mine is I’ve changed all the 1 to a link that reloads the html file itself when clicked.

  63. Michael Sync said

    am October 31 2007 @ 5:59 am

    >>The difference between your code and mine is I’ve changed all the 1 to a link that reloads the html file itself when clicked.

    what do you mean by “1 to a link”?? Are you posting the HTML code in comment? My comment system doesn’t allow the visitor to do taht.. you can reach me with this mail “mchlsync AT gmail DOT com”

  64. Sydney said

    am October 31 2007 @ 8:45 am

    Micheal, I’ve sent you my file, with the email subject “Re: [Michael Sync] New Comment On: Maintain Scroll Position of DIV using JavaScript - ASP.NET 2.0″

  65. Sydney said

    am October 31 2007 @ 8:56 am

    I wonder my problem is caused by duplicate cookie, because there is no path mentioned, so I’m looking into this.

  66. Sydney said

    am October 31 2007 @ 9:09 am

    Micheal, I found the problem and you might want to consider modifying your code.

    The problem is duplicate cookies, which I had suspected but not remembering why (this would be simple if I were paying attention to cookies)

    Once I’ve changed the javacode to include the path, things worked:

    document.cookie = “yPos=!~” intY “~!” ‘; path=/’;

    Please see jenseng DOT com slash archives slash 000040.html

    Thank you very much.

  67. Michael Sync said

    am October 31 2007 @ 6:45 pm

    Oh.. really.. Thanks a lot for inputs.. I will check this issue and will update my code…

  68. russell said

    am November 1 2007 @ 4:43 pm

    I used you code example and it works great. A requirement that I have on my current project is to have headers above the displayed scroll list data that remain aligned with the data and here is the key point - The headers must remain visible and not scroll with the data. I had the headers and scroll list data working and then I attempted to implement you code example while maintaining the above indiocated header requirement. I have tried numerous code variations but I can not get the headers to remain visible while the data scrolls and the page renders back to the latest scroll position. Any assisatnce would be greatly appreciated.

  69. Michael Sync said

    am November 1 2007 @ 7:02 pm

    Which headers are you talking about? Grid Header or Table Header?

    Normally, we used CSS expression to keep the position of header.. but CSS expression doesn’t work in non-IE browsers….

  70. dibs said

    am November 3 2007 @ 6:49 pm

    Michael, thanks for this extremely useful code. It’s straightforward and elegant. Great job!

  71. russell said

    am November 5 2007 @ 9:27 am

    I am using table headers. My jsp file looks something like the following:

    Your Scroll Position Logic Here

    Hope this helps!!!

  72. russell said

    am November 5 2007 @ 9:33 am

    OOPS!! Not sure why provided jsp code did not show up in previous reply. Any suggestions on how a can provide jsp code snippet. Also, our project is using IE browser.

    Thanks,

    Russell

  73. Tejal said

    am November 28 2007 @ 12:07 am

    Hi,
    I have used above code. Its working fine but with one problem.

    In the div’s onclick event I m calling function to set scrollTop.

    Now before this line document.getElementById(”myDIV”).scrollTop = strPos;
    if I m putting any kind of alert then its working fine. I am getting exact scroll position. But if I remove alert then its not working.
    Any idea ?
    Thanks,
    Tejal

  74. ravi said

    am December 2 2007 @ 10:49 pm

    Hi,

    Firstly Thank you for providing such a nice example.Its working with vs2005.i have downloaded the example and checked it.But i have created the sampe page in vs2003.its not working.when we have alert before setting the div pos to ’scrollTop’ its working.If we remove alert itz not.I want to explain the scenario of my application which is developing in vs2003.i have Header and Footer and in the middle of the page have div tag,all the controls are palced in it.Also it does have a Grid which we can add the rows dynamically.No control is outside of Div.i want to retain the position div on postbacks.
    please help me out.

    Thanks in Advance,
    ravi

  75. Michael Sync said

    am December 3 2007 @ 8:53 am

    Hi ravi,

    It might be probably cuz of adding the row dynamically. When you are showing the alert(), it will work fine since all rows are already added while this alert is showing.

    What you need to do is that you should call that function after adding the rows. meaning you should set the scrolltop position after all rows from grid have been build… I don’t have VS 2003 installed on my machine so I’m not able to make a sample for you.. I hope you can follow the tips and make your code to work..

    Hi Tejal,
    Sorry for late reply. Your problem may be the same as Ravi’s problem.. so, please read my comment above..

    Hi russell,

    You can either mail me or post the code in codeproject forum.. I will be there the most of time..

  76. Ravi said

    am December 3 2007 @ 10:00 pm

    Hi Michael,

    Thnaks for the quick response.Before i leave yesterday i have placed the same javascript code in my application to check how it works.Fortunately my problem got solved and its working fine.

    In the reply you have stated “What you need to do is that you should call that function after adding the rows. meaning you should set the scrolltop position after all rows from grid have been build”.Based on my knowledge i understood in this way in which we are calling the function in ‘window.onload’.How cuz it be possible to call it after building the rows?please elaborate?

    Thanks in advance,
    Ravi.

  77. Tejal said

    am December 3 2007 @ 10:32 pm

    Hi,
    Thanks for your reply.
    I solved above problem.

  78. Brad said

    am December 4 2007 @ 7:55 am

    Hi, I’m using an updatepanel, and when I look at my source through the view-> source it shows my div without an id. this would mean that if I try get the element id, it won’t get it by the id. anything I can do to stop this?

    thanks in advance,
    brad

  79. Brad said

    am December 4 2007 @ 8:06 am

    okay, nevermind, I found it. but I’m still having a problem with my div scroll still returning to the top. any way I can stop that?

  80. Michael Sync said

    am December 4 2007 @ 9:32 am

    >>How cuz it be possible to call it after building the rows?please elaborate?

    we call this function on window.load because we wanna set the position as soon as the page get loaded… but for your case, I think the row are dynamically added at run time.. so, those rows may not available when the page is loaded. at that time, you can’t set the position onload.. so, what you should do is that you should call this function after all of the rows are loaded.

    Hi Brad,

    I don’t have that much experiences in using ASP.NET ajax. I used to use ajax in my problem but I don’t use ASP.NET ajax. so, ..

    I’m still having a problem with my div scroll still returning to the top.

    i think the function that set the position of div doesn’t get invoked. so, try to invoke this function from your code..

  81. Brad said

    am December 5 2007 @ 8:02 am

    hmm, okay I’ve attempted to put the javascript (the window dot onload function without the actual function) into a string builder in my page load (asp.net C#). this has worked with alerts, so it should have worked then. I am seeing that the onscroll is getting the title bar to show numbers. so that section of the function is working. is there, perhaps, a method of creating a static variable, maybe in a class, and assigning to the variable. then , on the page load, get that static variable and set the scroll to that?

    I’m thinking that perhaps the document.cookie may not be going too well with the ajax, but I cannot be too sure about that.

    thanks in advance,
    Brad

  82. Ravi said

    am December 5 2007 @ 10:04 pm

    Hi Brad,

    If you accomplish the scenario please post the code in the Blog.

    Regards,
    Ravi

  83. Brad said

    am December 6 2007 @ 11:51 pm

    okay, done some more research, put in a few alerts here and there, and I’ve found a rather interesting thing. okay, I started off by increasing the cookie expiry date to 1 hour. then I put an alert in the window onload that pops up with the value. I then refreshed the screen. boom! we have a position change. I now know what the error is. it’s between my keyboard and my chair. AJAX does not fire the window onload because it partly refreshes the screen. so how i fixed this was a bit specific to my needs, but in C# in the page load I created a string builder and then put my alert and the position setting code. when I click on a button, boom! I got an alert, and then it scrolled to the correct place. I can’t post the code here since it’ll get blocked, so if anyone needs the code just post your email, and I’ll try get back to you.

  84. Michael Sync said

    am December 7 2007 @ 12:06 am

    Hi Brad,

    Thanks for sharing the solution with us. Could you please mail it to me? You can reach me with this id mchlsync AT gmail DOT com. I will upload it to my website and will post the link here to share with everybody..

    Thanks. :)

  85. Brad said

    am December 7 2007 @ 4:09 am

    Have sent it, hopefully you’ll be able to get it soon ^^

  86. Lloyd said

    am December 10 2007 @ 4:12 pm

    hi,
    I tried your code it works fine but I want to delete cookie in same page when user clicks another button. How can i do that please help….

  87. Lloyd said

    am December 10 2007 @ 4:17 pm

    actually let me put it specif way i want.
    1) First time cookie is null. Once user clicks search records are displayed in Gridview which is inside Panel.
    2)Next user scrolls down and selects a record by clicking HyperlinkField in grid view. he navigates to another page.
    3)user comes back to same page and scroll position of Panel should be maintained.
    I was able to do that using your code.
    But when again user clicks Search button i want to set default scroll position which is not happening.

  88. Michael Sync said

    am December 10 2007 @ 6:59 pm

    How can i do that please help….

    Ya. You can delete the cookies by setting the expired date.

    when again user clicks Search button i want to set default scroll position which is not happening.

    You mean, you want to reset the scroll position? You can set the top position of DIV on clickevent of your button..

  89. lloyd said

    am December 11 2007 @ 7:42 am

    thanks for reply.
    i tried giving expiry date but it doesnt expire as i need to close browser.
    My button is in user controls and it is difficult for me to do changes.
    document.cookie = ‘yPos=!~’ + intY + ‘~!’ + ‘; expires=Thu, 01-Jan-70 00:00:01 GMT’;
    This is how i have set expiration date.
    Tell me when will cookie expire if i se this.
    When user clicks another button i thought page refreshs and cookie wont be set as I had set it to expire but scroll position remains same.
    How can is set default poistion of grid again back or kill this cookie.

  90. Awais said

    am December 11 2007 @ 10:33 pm

    Thanks dude, it helps me a lot. That is what i am looking for.

  91. brad said

    am December 13 2007 @ 10:44 am

    hmmm, make sure the expiry date is set in the onclick (if using html and javascript) or in a string builder (if using C# or other such lang). otherwise, if that still does nada, try setting the val “intY” to 0. that’s the top of the scrollbar.

  92. Marcio said

    am January 4 2008 @ 11:31 am

    I am currently working on a ASP.net 2.0 web site which contains Ajax . I have a page with a UpdatePanel, and inside the pabel is a TabControl. Inside on one of the tabs, there is a div with a gridview.

    I tried the example in the ScrollDivTest project, but div.scrollTop does except the value from txt.value.

  93. Michael Sync said

    am January 4 2008 @ 9:37 pm

    Hi Marcio,

    div.scrollTop does except the value from txt.value.

    I’m not so sure what you meant by this. What error are you getting?

  94. Marcio said

    am January 7 2008 @ 7:43 am

    Michael,

    I am not getting an error. I am using the ScrollDivTest project. The div.scrollTop always return 0 in the function GetDivPosition (Default.aspx).

  95. Marcio said

    am January 8 2008 @ 8:57 am

    Michael,

    I finally figured out the problem. I had the tab container inside a update panel. I remove the updated panel, and added one update panel per tab.

    Thank you for your help.

    Marcio

  96. Michael Sync said

    am January 9 2008 @ 6:24 am

    Thanks for informing me, Marcio. I’m glad to hear that you have solved your problem..

  97. Dave said

    am January 20 2008 @ 6:07 pm

    Just what I was looking for - it’s been a major ‘I’ll get round to doing something about it’ bug for a long time.

    I am a little concerned that ‘onscroll’ is not a valid attribute of Panel - but it runs without a problem anyway (on .NET 2.0 and under IE6x) - not sure what will happen with .NET 3.0 and VS2008…

    If your page posts back to create a ‘new page number’ adding this to the next page and last page buttons returns the scrollbar back to the top position…

    Dim ResetScroller As String = “” & _
    “function resetScroll() { ” & _
    “document.getElementById(”"Panel1″”).scrollTop = “”0″”; } ” & _
    “”
    Page.ClientScript.RegisterStartupScript(Me.GetType(), “ResetScroller”, ResetScroller)

    Me.Button1.Attributes.Add(”onClick”, “resetScroll(); “)
    Me.Button2.Attributes.Add(”onClick”, “resetScroll(); “)

    Thanks again for providing an reliable ‘Ajax compliant’ solution…

  98. Ankur said

    am February 19 2008 @ 11:17 pm

    seems to be a good solution..however is there any means in order to maintain the scroll position after a page has been submitted? I have a form on a page and this form is quite at the bottom part of the page..if some one fills and submits the form, i woukd want the scroll to maintain there and not come up as usually happens with normal posts..a using ASP 3.0..
    is is possible? a reply will be appreciated..

    thnx ..ankur

  99. Ankur said

    am February 20 2008 @ 3:21 am

    actually..i want exactly this fucntionality in my page

  100. JayJay said

    am April 4 2008 @ 2:41 pm

    Micheal, Dave

    If you have solution to this problem, please send it to me.
    I am trying to maintain scroll position of a div inside UpdatePanel. Here’s what I have… However my div always scrolls to the top. I know I don’t get onload callback since I am using update panel, so I call SetDicPosition javascript in the code behind. still doesn’t work. Everything works fine if there is no UpdatePanel. In my case, I have to use UpdatePanel..

    I tried using the following javascript

    function SetDivPosition()
    {

    var strCook = document.cookie;
    if(strCook.indexOf(”!~”)!=0)
    {
    var intS = strCook.indexOf(”!~”);
    var intE = strCook.indexOf(”~!”);
    var strPos = strCook.substring(intS+2,intE);
    document.getElementById(’divID’).scrollTop = strPos;
    }

    }

    function GetDivPosition()
    {
    var intY = document.getElementById(’divID’).scrollTop;
    document.title = intY;
    document.cookie = “yPos=!~” + intY + “~!”;
    }

  101. Michael Sync said

    am April 4 2008 @ 7:37 pm

    Hello Jayjay,

    Have you tried Brad’s code? He wrote the code at page_load event and He added “path” in cookies. Can you tried to do that? sometimes, path is important..

  102. Dave said

    am April 4 2008 @ 8:39 pm

    This solution works really well for me!

    Create a public class :-

    =================================================

    Public Class Scripts

    Public Function LoadScroll(ByVal panel As Panel) As String

    Dim sb As New StringBuilder

    sb.AppendFormat(”var scrollTop{0};”, panel.ClientID)

    sb.AppendFormat(”var scrollLeft{0};”, panel.ClientID)

    sb.AppendFormat(”Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler{0});”, panel.ClientID)

    sb.AppendFormat(”Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler{0});”, panel.ClientID)

    sb.AppendFormat(”function BeginRequestHandler{0}(sender, args)”, panel.ClientID)

    sb.Append(”{”)

    sb.AppendFormat(”var elem=document.getElementById(’{0}’);”, panel.ClientID)

    sb.AppendLine(”if (elem)”) ‘added

    sb.AppendLine(”{”) ‘added

    sb.AppendFormat(”scrollTop{0}=elem.scrollTop;”, panel.ClientID)

    sb.AppendFormat(”scrollLeft{0}=elem.scrollLeft;”, panel.ClientID)

    sb.AppendLine(”}”) ‘added

    sb.AppendLine(”}”)

    sb.AppendFormat(”function EndRequestHandler{0}(sender, args)”, panel.ClientID)

    sb.AppendLine(”{”)

    sb.AppendFormat(”var elem=document.getElementById(’{0}’);”, panel.ClientID)

    sb.AppendLine(”if (elem)”) ‘added

    sb.AppendLine(”{”) ‘added

    sb.AppendFormat(”elem.scrollTop=scrollTop{0};”, panel.ClientID)

    sb.AppendFormat(”elem.scrollLeft=scrollLeft{0};”, panel.ClientID)

    sb.AppendLine(”}”) ‘added

    sb.AppendLine(”}”)

    Return sb.ToString

    End Function

    Public Sub LoadScroll(ByVal panel As Panel, ByVal page As Page)

    Dim s As String = LoadScroll(panel)

    If Not page.ClientScript.IsStartupScriptRegistered(panel.ClientID) Then

    page.ClientScript.RegisterStartupScript(page.GetType, panel.ClientID, s, True)

    End If

    End Sub

    End Class

    ==============================================

    Then call it from the page where the panel in this instance is panel6

    Dim vLoadScroll As New Scripts
    Dim vLoadPanel As String = vLoadScroll.LoadScroll(Panel6)
    ScriptManager.RegisterStartupScript(Me, Me.GetType, “scrollLoad”, vLoadPanel, True)

  103. Bala said

    am May 1 2008 @ 1:57 am

    You are great that works like a charm………

  104. Mitch said

    am May 22 2008 @ 7:35 am

    Nice post Michael. I’ve been looking for this solution for a while now but I really didn’t want to use cookies. Seems like it might be the only way. One question though: Any idea how long the cookie lasts for?

  105. Mitch said

    am May 22 2008 @ 7:44 am

    PS. I think the first post from ria was meant to say ‘header row’. I also am interested if you have any tips or tricks for this.

Comment RSS · TrackBack URI

Leave a comment

Name: (Required)

eMail: (Required)

Website:

Comment: