Sometimes it is important that one part of a page is always visible. Depending on the nature of the site, this can be an ad banner (Geocities, now a part of Yahoo!, was among the first to implement this) or a navigation. Once again, a <div> element will be positioned. The special feature of a sticky navigation is that the position stays the same even if the user is scrolling. So the preceding code is used to call the positioning code both when the page loads and when it scrolls. For calculating the new position, you have to calculate the current scroll offset. Internet Explorer provides document.body.scrollLeft and document.body.scrollTop for that; the other browsers use window.pageXOffset and window.pageYOffset. The following code maintains the position of the navigation, and Figure 5.8 shows the result. Maintaining the Position of an Element (sticky.html; excerpt)
Figure 5.8. A sticky navigation with JavaScript. |