Reply to comment
Note: This is not my code, but a friend of mine's. 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 JavaScript, which I recommend, then you could rewrite the function above to use the CSS Class finder function, which would allow you to scroll to an element without needing the id attribute set. |
|||
