Archive for August, 2007

Automatically scrolling a div containing divs

Friday, August 17th, 2007

I have a table-of-contents in  a course. The table of contents is a <div> that contains other <div>s. The table of contents can have so many items that it requires scrolling. I also have previous/next buttons that can switch from one item in the table-of-contents to the next. I had to make sure the current-item is always scrolled into view.

 The first part of this solution is to find the Y position of an item within the table of contents. I found a great public-domain function from firetree (the original code is from quirksmode).

Now, I had to write the scrolling code:

 // get the id of the TOC container
 var oSections = document.getElementById(‘tocContainer’);
 
 // get the y position of the TOC section container
 var nSectionsY = findPosY(oSections);
 
 // get the y position of the selected item
 var nItemY = findPosY(document.getElementById(sItem)); 
 
 // adjust the item height to be in the coordinate space of the container
 nItemY -= nSectionsY;
 
 // get the height of the container and pull off the “px” part on the end
 var nHeight = parseInt(oSections.style.height);
 
 // see if the complete item is greater than the height of the container
 if ((nItemY+21) > nHeight) {
  // it is, scroll the selected page into view
  oSections.scrollTop = nItemY;
 } else {
  // see if the item is showing given the current scroll position
  if (oSections.scrollTop > nItemY) {
   // it is not, scroll the item into view
   oSections.scrollTop = nItemY;
  }