Developers often encounter situations where they need to maintain scroll position on a control after a postback to the server has occurred.
Take the following scenario:
Say you have a web form containing a div that contains a datalist. The rows of your datalist, (along with other controls) contain checkboxes. Now every time a checkbox is checked and unchecked, you need to do some server side validation in code before letting the user proceed.
Your datalist contains tons of rows and by default, each time a validation occurs, the datalist “refreshes” and scrolls back to the top. This can easily get annoying for users and can ruin the general user experience. But we can fix it with a bit of JavaScript 🙂
This explanation is based on C# and ASP.NET but you can easily apply the principle to any language.
First add a hidden dummy input to your form. Since it’s hidden, you can just add it anywhere. Like this:
<input id="Y" type="hidden" name ="Y" runat="server" />
Now add the following JavaScript code to the relevant section of your HTML:
<script type="text/javascript"> function getScrollPosition() { var y; if (document.getElementById('divDatalist').scrollTop) { y = document.getElementById('divDatalist').scrollTop; } else { y = document.body.scrollTop; } document.getElementById('<%= Y.ClientID %>').value = y; //alert(document.getElementById('<%= Y.ClientID %>').value); } function setScrollPosition() { var y = document.getElementById('<%= Y.ClientID %>').value; //alert(document.getElementById('<%= Y.ClientID %>').value); if (y == null) { //alert('Bad Hidden Field Id!'); } else { document.getElementById('divDatalist').scrollTop = y; } } window.setInterval('getScrollPosition()', 350); window.onload = setScrollPosition; </script>
That’s it. You’re done.
The scroll position on your datalist will now be maintained after postback.
Note: ASP.NET has the MaintainScrollPositionOnPostback page directive which gets or sets a value indicating whether to return the user to the same position in the client browser after postback. This can be set to true to maintain scroll position on the page after postback. However, this will not work for a datalist within a div. To handle embedded controls like that, use the JavaScript code given above.
Very Nice it is work for me.