Blog
Skip to end of metadata
Go to start of metadata

A friend of mine wrote this code and it's been helpful to me over the years. It may no longer work in all modern browsers.

When writing AJAX websites, developers sometimes need to scroll to a particular element within the DOM on the page. The most common approach, using javascript, is:

/**
* Scroll to an element (by id attribute or name attribute of the anchor tag )
*/
function scrollToElement( elementName ) {
  if ( elementName ) {
    window.location = "#" + elementName;
  }
}

However, this approach is not cross-browser compatible because some browsers will refresh the page. Since this is mostly necessary in an AJAX application, refreshing is most likely NOT desired.

So my friend came up with the following JavaScript that I have found to work in most modern browsers.

/**
* Scroll to an element (only works by id attribute)
*/
function scrollToElement(elementID) {
  var theElement = document.getElementByID( elementID );
  if(theElement != null) {
    var selectedPosX = 0;
    var selectedPosY = 0;
    while( theElement != null ) {
      selectedPosX += theElement.offsetLeft;
      selectedPosY += theElement.offsetTop;
      theElement = theElement.offsetParent;
    }
    window.scrollTo( selectedPosX, selectedPosY );
  }
}

If you use the prototype.js, dojo, jquery or some other javascript library, then you could rewrite the function above to use a CSS class finder function, which would allow you to scroll to an element without needing the id attribute set.

  • No labels