How do I keep the scroll position independent of postback?

I have a regular time interval event in javascript that clicks on an asp button. The app is a frequent chat and I have to refresh the gridview (which is inside the panel) to check for new chats. But every time the button is clicked and the gridview is refreshed, the pane is scrolled to the top (i.e. the scrollTop value becomes 0). I've tried this but to no avail: -

    <script type="text/javascript">
    function refresh() {
        setInterval(function () {
            var xtop = document.getElementById("Panel1").scrollTop;
            document.getElementById("Button2").click();
            document.getElementById("Panel1").scrollTop = xtop;
        }, 1000);
    }
    </script>

      

+3


source to share


1 answer


If you want to keep the scroll position between postbacks, in your function, refresh()

you can store the scroll position value in a hidden box that you put somewhere in your HTML: <input type="hidden" id="scroll"></input>

using JavaScript

document.getElementById("scroll").value = document.getElementById("Panel1").scrollTop;

      

There are other options for storing data such as cookies and ASP.NET ViewState, but a hidden field is easiest for this purpose. Then you can read that value from the hidden field on DOM load and scroll the window to that position.



However, if you send back every second to check for new messages, you probably have a big problem. This kind of functionality is better done asynchronously with AJAX. This will take a bit of research as I'm not sure about your implementation here, but essentially you will be using JavaScript to ask the server if there are new messages and load them from the server asynchronously, thus eliminating the use of postbacks.

Here is Mozilla's introduction to AJAX.

0


source







All Articles