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
*/

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
hey Michel
Thank you very muxh for such a nice post.
it working absolutely fine.
people like u make our job easy.
thanks again
Thanks for the script. I ran into a similar reqiurement and was thinking of the same cookie solution. You script saved my time.
I am trying to use your code in a AJAX Update panel
But the function you suggested dosent work kinly suggest
Thanks,
Amaan Kazi
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);
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.
can you explain me the scrollbar maintanance after selecting the radio button in the page event.i am using 1.1 version.
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 ……
My html tags in my original message seems to be all gone.
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
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..
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.
>>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”
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″
I wonder my problem is caused by duplicate cookie, because there is no path mentioned, so I’m looking into this.
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.
Oh.. really.. Thanks a lot for inputs.. I will check this issue and will update my code…
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.
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….
Michael, thanks for this extremely useful code. It’s straightforward and elegant. Great job!
I am using table headers. My jsp file looks something like the following:
Your Scroll Position Logic Here
Hope this helps!!!
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
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
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
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..
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.
Hi,
Thanks for your reply.
I solved above problem.
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
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?
>>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 think the function that set the position of div doesn’t get invoked. so, try to invoke this function from your code..
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
Hi Brad,
If you accomplish the scenario please post the code in the Blog.
Regards,
Ravi
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.
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. :)
Have sent it, hopefully you’ll be able to get it soon ^^
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….
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.
Ya. You can delete the cookies by setting the expired date.
You mean, you want to reset the scroll position? You can set the top position of DIV on clickevent of your button..
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.
Thanks dude, it helps me a lot. That is what i am looking for.
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.
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.
Hi Marcio,
I’m not so sure what you meant by this. What error are you getting?
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).
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
Thanks for informing me, Marcio. I’m glad to hear that you have solved your problem..
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…
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
actually..i want exactly this fucntionality in my page
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 + “~!”;
}