Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain scroll position of a div within a page on postback

I have a div within an aspx page with overflow set to auto. The contents of the div are dynamically created and consists of a list of link buttons.

<div id="div1" style="overflow: auto; height: 100%;">
.....
</div>

When I scoll down in the div and click on any of the link buttons, the page reload loses the scroll position inside the div and takes me to the top of the div. Is there any way to prevent that?

Note that this is for a div inside the page. Page.MaintainScrollPositionOnPostBack() does not work.

like image 641
Nikhil Avatar asked Jul 07 '09 20:07

Nikhil


People also ask

How do you make a Div fixed position while scrolling?

To make div fixed scrolling to that div with CSS, we can use the position: sticky CSS property. position: -webkit-sticky; position: sticky; top: 0; z-index: 1; to set position to sticky and z-index to 1 to make the element with the sticky position show on top after we scroll to it.

What is MaintainScrollPositionOnPostBack?

On long Web pages, this means that the user has to scroll the page back to the last position on the page. When the MaintainScrollPositionOnPostBack property is set to true , the user is instead returned to the last position on the page. You set the MaintainScrollPositionOnPostBack property in the @ Page directive.

How maintain scroll position react JS?

By default you can set the value of scrollPosition is 0 . Here I have used the sessionStorage to maintain the scroll position for demo purpose. You can also use the context API or redux store to manage it.


1 Answers

As Jeff S mentioned one way to handle this situation is using javascript to track the scroll position of the div and each time the page loads reset the scroll position to its previous value.

Here's some sample code:

<html>
<body onload="javascript:document.getElementById('div1').scrollTop = document.getElementById('scroll').value;">
    <form id="form1" runat="server">
    <input type="hidden" id="scroll" runat="server" />
    <div id="div1" style="overflow: auto; height: 100px;" onscroll="javascript:document.getElementById('scroll').value = this.scrollTop">
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        ...........<br />
        <asp:LinkButton ID="LinkButton1" runat="server" Text="test2"></asp:LinkButton>
    </div>
    <asp:LinkButton ID="LinkButton2" runat="server" Text="test1"></asp:LinkButton>
    </form>
</body>
</html>

In practice I wouldn't put the javascript directly in the elements but its just an example. You could also store the scroll position in a cookie instead.

like image 127
joshb Avatar answered Oct 21 '22 18:10

joshb