Introduction
Hi, friends. After reading this article, you will be able to maintain the scroll position in panel
or div
of any Web page. There are lots of techniques to do this, but I was facing a problem so I used the below code and solved the problem. If you want to maintain the scroll position of a Web page, then it is easy to do so through the ASPX page property.
MaintainScrollPosition = "true"
But here the problem is with div
or panel
in Web page.
Background
I wanted to maintain the scroll position of div
or panel
in a Web page. I got a solution for the same but after implementing it, I was faced with another problem. If I put an alert
before setting the position, I was getting the desired output. But when I removed the alert
, it was not working. That was strange! So I implemented the below code to achieve the same.
This article will describe every single line of code.
Using the Code
This is the code in JavaScript from which we can do the same thing. But the problem arises at one point.
First of all, put one div
and give Id = "myDIV"
. Assign height = 200px
.
Now take on gridview
and put into div
. Bind data to gridview
and make sure you have date in gridview
so div
can scroll.
Now copy and paste this code in the ASPX page in the script
tag:
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("myDIV").scrollTop = strPos;
}
}
function SetDivPosition()
{
var intY = document.getElementById("myDIV").scrollTop;
document.cookie = "yPos=!~" + intY + "~!";
}
Now after scrolling div
when clicking on the last row of gridview
, it's again going in the first row. Here I have put an alert
just above one line. See the code below:
alert("Any Alert.... Hello Friend");
document.getElementById("myDIV").scrollTop = strPos;
Now, when I run it again after clicking ok on the alert
, it works perfectly....!!
So now I tried to solve this bug. I searched a lot, but had no luck. Here is one solution for that which I came up with.
Add one HTML hidden field and set Id = myHidden
.
function SetDivPosition()
{
window.setTimeout("SetNow('" +
document.getElementById("myHidden").innerHtml + "')",200);
}
var strPos;
function SetNow(strPos)
{
document.getElementById("myDiv").scrollTop = strPos;
}
function GetDivPosition()
{
document.getElementById("myHidden").innerHtml =
document.getElementById("myDiv").scrollTop;
}
Here is the output that we would like to see. Really short and sweet code.
Points of Interest
You need to try until you get your desire output. There are lots of ways to achieve it.
History
- 1st December, 2007: Initial post