Maintain scroll position on postback for gridview or div


Problem Statement:

There can be scenarios wherein your end users would appreciate to see the screen intact even after postback. In ASP .Net we use the MaintainScrollOnPostback property for the page to handle the page’s scroll position. But this will not handle the case when you have gridviews wrapped in divs and having a scroll (usually the overflow property). To maintain the scroll on postback in this case is not directly possible.

Check the gridview image above. There are a lot of checkboxes in it and the width of the grid goes beyond the screen size. Hence i have given a scroll to the div wrapping it. Under normal scenarios when the user clicks on the refresh button or Submit button or F5 in the browser, the scroll position of the div will not be retained. Instead it will look something like what you see below:

However the end user would really appreciate if the scrollbar also had maintained its position after the postback.

Solution Approach:

The solution for this kind of a problem could be easily done through javascript and a hidden variable on the page.

Solution:

Step 1 : In the scrolling div, register the onscroll event for storing the scroll position of the div.

<div id=”grdScr” onscroll=”javascript:setScroll();” >
<asp:GridView ID=”gdvPostings” runat=”server” GridLines=”None” CellPadding=”0″ CellSpacing=”0″
BorderWidth=”0″ AutoGenerateColumns=”false” CssClass=”jqPst” HeaderStyle-VerticalAlign=”Bottom”
OnRowDataBound=”gdvPostings_RowDataBound” EnableViewState=”true”>
This function will take the scrollLeft value of the div and store it in a hidden variable on the page.

Step 2 : In the page code behind, you should register the script that should run in the page load. This should take care of setting the div scroll to the state which it was, before the postback.

ClientScript.RegisterStartupScript(typeof(Page),”scroller”, “scrollToVal();“);

This function will set the value of the div scrollLeft property to the value in the hidden variable.

Step 3 : Place a hidden variable in the page, with runat server attribute. If you dont make it server side, the value will not be retained.

<input type=”hidden” id=”hdnScrPs” runat=”server” value=”” />

Step 4 : Load the javascript functions in the page.

$(document).ready(function(){

$(“#grdScr”).scroll(function(){

$(“[id$=’hdnScrPs‘]”).val($(“#grdScr”).scrollLeft());

});

});

 

function scrollToVal() {

$(“#grdScr”).scrollLeft($(“[id$=’hdnScrPs‘]”).val());

}

I have used jQuery in this case. You can use normal javascript if you need.

 

Alternative Approach (using HTML5 LocalStorage – valid for IE 8 & above N rest of the world):

Step 1: Bind a scroll event to the grid’s wrapper div, capture the scrollLeft value and store it in localstorage

Step 2: On page load, set the scroll position back to the grid’s wrapper div

 $(document).ready(function(){

// Check if the localstorage has values on page load, if yes, set the scroll left for the wrapper div

var gridScrollPos = localStorage.getItem(“GridScrollPosition”),

$grid = $(“#grdScr”);

gridScrollPos && $grid.scrollLeft(gridScrollPos);

//Bind the Scroll event to the grid to capture the scroll position and store it in localstorage

$grid.on(‘scroll’, function(){

localStorage.setItem(“GridScrollPosition”, $(this).scrollLeft());

});

});

Hope this helps. Feel free to post your queries.

Update(s):

  • The hdnScrPs id selector is changed to accept values irrespective of the prefix that is appended to it while getting rendered on the HTML, by using $(“[id$=’htnScrPs’]”) instead of $(“ctl00_cphMain_hdnScrPs”)
  • Using $.scrollLeft instead of javascript scrollLeft
  • Using $.scroll instead of javascript onscroll event
  • Added an alternate approach using localstorage

 

  1. can you post it using javascript please. It is not working for me

    Reply

  2. It not working in my case.. Even I don’t get any error on console.

    Reply

    1. Hi Noman,
      Sorry to hear that it is not working for you. I have made a few updates to the script above to avoid selecting the hidden variable using ‘ctl00_’ prefix and also to use $.scrollLeft instead of the javascript equivalent. Try giving it a shot.

      To help you debug the issue, try chrome developer toolbar –> Console and execute the following commands, after scrolling the div a few pixels to the right:

      $(“[id$=’hdnScrPs‘]”).val(); /* This should give you the current scroll position; */

      Logic: As and when the user scrolls the div section, keep storing the scrollLeft value in the hidden variable. Since the hidden variable is a server control (runat=”server” and the page has viewstate enabled, this hidden field value will persist even when the page refreshes. Once the page refresh, you can retrieve this value and set it back to the scrollLeft.

      Instead of hidden variable, you may also use localstorage (http://www.w3schools.com/html/html5_webstorage.asp) to store the scroll value.

      Reply

  3. It’s very simple to find out any matter on web as compared
    to textbooks, as I found this piece of writing at this web site.

    Reply

  4. OnScroll is not supported by div tag.

    Reply

  5. Please can you provide same logic with normal Java script

    Reply

    1. You can try the following: [watch out for browser compatibility issues in Opera]

      Replace the existing functions with this one.

      function setScroll() {
      document.getElementById(‘ctl00_cphMain_hdnScrPs’).value=document.getElementById(‘grdScr’).scrollLeft;
      }

      function scrollToVal() {
      document.getElementById(‘grdScr’).scrollLeft = document.getElementById(‘ctl00_cphMain_hdnScrPs’).value;
      }

      Reply

  6. It Is not working !

    Reply

  7. Thanks aackose, its really helpful. Thanks a lot

    Reply

Feel free to leave a reply here...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: