views:

442

answers:

4

I have a div as such:

<div style="overflow-y: scroll; height: 260px">

I contains a few hundred records and allows me to select an item to populate a formview control below it.

The problem is that when the page posts-back, the scroller position goes back to the top of the div. I want to try and maintain its position so that the selected record is still visible.

Any ideas?

A: 

Disclaimer - not my code, but I've seen this used before:

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("divTest").scrollTop = strPos;
      document.getElementById("divTest").scrollTop = strPos;
    }
  }
  function SetDivPosition(){
    var intY = document.getElementById("divTest").scrollTop;

    document.cookie = "yPos=!~" + intY + "~!";
  }

The idea is to store the position of the scrollbar in a cookie. Another (better?) option would be to store it in a hidden field (or fields). Hope that gets you going...

Dan Diplo
A: 

ASP.NET has this built in all you need to do is include the MaintainScrollPositionOnPostback in your page directive.

<%@ Page Language="C#" MaintainScrollPositionOnPostback="true" %>
I doubt that works on embedded divs, just the main page in general.
FlySwat
Yeah I'm not sure this will work on DIV's contained within the page. Although I haven't tried it.
Chris Pietschmann
Lol i so didn't read the question properly, sorry folks
+1  A: 

Place something like:

 <asp:Hidden id="hdnScrollPos" runat="server"/> in your aspx.

Then, some javascript like:

var hdnScroll = document.getElementById(<%=hdnScrollPos.ClientID%>);
var bigDiv = document.getElementById('bigDiv');
bigDiv.onscroll = function() {
     hdnScroll.value = bigDiv.scrollTop;
}

window.onload = function () { 
    bigDiv.scrollTop = hdnScroll.value;
}
FlySwat
A: 

Hold Your (Scroll) Position - Don't let a postback reset your page's scroll position

Replace thebody with document.getElementById("divTest")

If you worry that the onscroll event does not work in opera/ff, you can try changing

thebody.onscroll=SaveScrollLocation;

to

setInterval('SaveScrollLocation()", 500);
mangokun