Creating a Sticky Navigation


window.onload = positionNavigation; window.onscroll = positionNavigation; 

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)

<script language="JavaScript"   type="text/javascript"> function positionNavigation() {   var nav = document.getElementById("navigation");   var x, y;   var navwidth = 155;   if (window.innerWidth) {     x = window.innerWidth + window.pageXOffset          navwidth;     y = window.pageYOffset + 10;   } else {     with (document.body) {       x = clientWidth + scrollLeft - navwidth;       y = scrollTop + 10;     }   }   nav.style.left = x + "px";   nav.style.posLeft = x;   nav.style.top = y + "px";   nav.style.posTop = y; } window.onload = positionNavigation; window.onscroll = positionNavigation; </script> <h1>My Portal</h1> <div  style="position: absolute; background-color: #eee; border: 1px solid"> <a href="http://www.samspublishing.com/">Sams Publishing</a><br /> <a href="http://www.amazon.com/gp/product/ 0672328801">This book at Amazon</a><br /> <a href="http://www.hauser-wenz.de/blog/">Author's weblog</a> </div> 

Figure 5.8. A sticky navigation with JavaScript.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net