Michael Sync

Michael Sync

Crisp, minimal personal blog

30 Jun 2006

Maintain Scroll Position of DIV using JavaScript – ASP.NET 2.0


Some people have some problems in maintaining the position of the DIV. Initially, The most of people are using htc for solving this problem. but there are so many disadvantages of using htc such as it works only in Internet Explorer, it doesn’t work properly with Visual Studio 2005 and so on.

Finally, I got the solution for solving this problem.. Using Javascript for keeping the scroll position is the best way to go.. JavaScript helps us to know the current position of DIV. Plus, we can use HTTP Cookie for storing the value of the previous position of DIV tag.

Source Code: MaintainScroll.zip

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
window.onload = function() {
    var strCook = document.cookie;
    if (strCook.indexOf("!~") != 0) {
        var intS = strCook.indexOf("!~");
        var intE = strCook.indexOf("~!");
        var strPos = strCook.substring(intS + 2, intE);
        document.getElementById("grdWithScroll").scrollTop = strPos;
    }
}

function SetDivPosition() {
    var intY = document.getElementById("grdWithScroll").scrollTop;
    document.title = intY;
    document.cookie = "yPos=!~" + intY + "~!";
}

I have tested this code with IE6, 7 and Mozilla Firefox. It’s working fine. Please let me know if you have any problem with this code. Special Thanks to Jim Ross and Eric Pascarello.

UPDATED I got this email from Brad Alcock. He explained about his appraoch.

Hi. here’s the code with a very brief explanation on what goes on behind the scenes.

a little different to what you did, but sort of on the same track. I’m sure you can find a method of working around it to fit in with your post ^^

right, my div’s id was panel1, I basically created a cookie for the onscroll of the div in the function SetDivPosition(). the read cookie is read using the stringbuilder in the C# Page_load code underneath.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
function SetDivPosition() {
    var intY = document.getElementById("Panel1").scrollTop;
    var date = new Date();
    date.setTime(date.getTime() + (1 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
    document.cookie = "cookie1" + "=" + intY + expires + "; path=/";
    document.title = intY;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

Here is the string builder in the page Load. the part in the if(!IsPostback) is there so that when the page is loaded for the very first time, it removes any possibility of a cookie being there (incase the page is returned to within an hour. ) that means the scrollbar will not suddenly jump to a position at arb times like first time page is loaded.

Don’t forget to use System.Text; otherwise it will throw an error.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
protected void Page_Load(object sender, EventArgs e) {
  if (!IsPostBack) {
    StringBuilder sbScript = new StringBuilder();
    sbScript.Append("<script language='JavaScript' type='text/javascript'>");
    sbScript.Append("document.cookie = cookie1 + \"=\" + \"\" + -1 + \"; path=/\";");

    sbScript.Append("</script>");
    // Make use ScriptManager to register the script
    ScriptManager.RegisterStartupScript(this, this.GetType(), "@@@@MyCallBackAlertScript", sbScript.ToString(), false);

  }
  StringBuilder sbScript1 = new StringBuilder();
  sbScript1.Append("<script language='JavaScript' type='text/javascript'>");
  sbScript1.Append("var strCook = readCookie(\"cookie1\"); " +
    "document.getElementById(\"Panel1\").scrollTop = strCook;");
  sbScript1.Append("</script>");

  // Make use ScriptManager to register the script
  ScriptManager.RegisterStartupScript(this, this.GetType(), "@@@@MyCallBackAlertScript", sbScript1.ToString(), false);
}