In this blog, I will explain how to maintain scroll position of HTML div on PostBack in ASP.NET. HTML's div with the vertical scrollbar gets back to the original position after PostBack and hence to solve this problem, we need to retain its scroll position value, using JavaScript and then again apply to div after PostBack. This technique helps DIV not to lose its scroll position on PostBack.
HTML Markup
In HTML markup, given below, I have HTML's div with the vertical scrollbar for which we will maintain the scroll position on PostBack, HTML's HiddenField and an ASP.NET button to perform PostBack.
<script type="text/javascript">
window.onload = function() {
var div = document.getElementById("dvScroll");
var div_position = document.getElementById("div_position");
var position = parseInt('<%=Request.Form["div_position"] %>');
if (isNaN(position)) {
position = 0;
}
div.scrollTop = position;
div.onscroll = function() {
divdiv_position.value = div.scrollTop;
};
};
</script>
<div id="dvScroll" style="overflow-y: scroll; height: 260px; width: 300px"> This is a sample text <br /> This is a sample text <br /> This is a sample text br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> his is a sample text br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> This is a sample text <br /> </div>
<hr /> <input type="hidden" id="div_position" name="div_position" /> sp:Button ID="Button1" Text="Submit" runat="server" />
The output will look, as shown below.