Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain scroller position on Div after page postback (ASP.NET)

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?

like image 424
Dkong Avatar asked Jul 26 '09 13:07

Dkong


3 Answers

Place something like:

 <asp:HiddenField 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;
}
like image 155
FlySwat Avatar answered Oct 21 '22 19:10

FlySwat


Here is a more refined way of FlySwat's solution using JQuery which worked for me:

    var $ScrollPosition = $('#hfScrollPosition');
    var $ScrollingDiv = $('#pnlGroupDataContent');
    if ($ScrollPosition.length && $ScrollingDiv.length) {
        // Store scrolling value
        $ScrollingDiv.scroll(function () {
            $ScrollPosition.val($ScrollingDiv.scrollTop());
        });
        // Set scrolling
        $ScrollingDiv.scrollTop($ScrollPosition.val());
    }
like image 41
LinkedWith Avatar answered Oct 21 '22 18:10

LinkedWith


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...

like image 44
Dan Diplo Avatar answered Oct 21 '22 19:10

Dan Diplo