Maintain Scroll Position of ASP.NET Panel after postback

Asp.NET Panel is a div, so in following code, javascript is used to maintain scroll after postback and cookies is used to store scroll position. For first time, we need not to set scroll so it is detected using IsPostback property.


<script language="javascript" type="text/javascript">
var IsPostBack= '<%=IsPostBack.ToString() %>';
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);
if (IsPostBack=='True')
{
document.getElementById("<%=pnlTree.ClientID %>").scrollTop = strPos;
}
else
{
document.cookie = "yPos=!~0~!";
}
}
}
function SetDivPosition(){
var intY = document.getElementById("<%=pnlTree.ClientID %>").scrollTop;
document.title = intY;
document.cookie = "yPos=!~" + intY + "~!";
}

</script>

<asp:Panel ID="pnlTree" runat="server" Height="462px" Width="390px" ScrollBars="Auto" onscroll="SetDivPosition()">
….
</asp:Panel>


Replace pnlTree to your panel ID in above code and Enjoy it.

3 comments:

  1. What will happen, when the cookies are disabled ??

    Is there any other way to do that ?

    ReplyDelete
  2. Nisheeth,

    You can use hidden field to store scroll position. See following example:
    <body onload="javascript:scrollTo('scrollArea')" >
    <form id="Form1" method="post" runat="server">
    ...
    <div id="scrollArea onscroll="javascript:setScroll(this);"
    runat="server" style="vertical-align: top; height:200px; width:100%;
    overflow:auto;">
    ....
    </div>
    <input type="hidden" id="scrollPos" name="scrollPos" value="0"
    runat="server">
    ...
    </form>
    <script language="javascript">
    function setScroll(val) {
    document.Form1.scrollPos.value = val.scrollTop;
    }
    function scrollTo(what) {
    document.getElementById(what).scrollTop =
    document.Form1.scrollPos.value;
    }
    </script>
    </body>

    ReplyDelete
  3. Thanks Brother......
    Very Helpful For Me...............

    ReplyDelete