Navigation Bar in JavaScript

Net surfers do not really like that the pages are divided into several parts. This is not a good thing to get backlinks. However, this may sometimes be necessary when pages are too large, to save bandwidth.

We will show how to make a navigation bar, which will look as that:

Page First 1 2 3 4 5 >> Last

One can of course vary the presentation with a style sheet.

We want the navigation bar now show grayed link(s) to the current page and show in blue links to other pages.
This can not be done with the "a:active" attribute, because the color for visited pages outperforms the color of the active page.
Therefore by using CSS and JavaScript we will achieve this result.

HTML code of the navigation bar

<p>Page 
<span id="navbar"> <a class="navpage" href="page1.html" target="_parent">First</a> <a class="navpage" href="page1.html" target="_parent">1</a> <a class="navpage" href="page2.html" target="_parent">2</a> <a class="navpage" href="page2.html" target="_parent">>></a> <a class="navpage" href="page2.html" target="_parent">Last</a> </span> </p>

We will need the ID "navbar" to find part of code whose style have to be changed, and class "navpage" to change the style individually for each link.

Stylesheet

#navbar {  border:1px solid gray;  padding:2px; } 
.navpage {   color:blue; }
.graystyle {   color:gray; }

These descriptors will allow to change the color of links.

The JavaScript code

function pagebar()
{
  var links=document.getElementById('navbar').getElementsByTagName("a");
  var current = location.href;
  for (var i=0; i < links.length; i++)
  {
   if(links[i].href == current)
   {
      links[i].href = "";
      links[i].className='grayStyle';
   }
 }
} 

The script builds a list of all the links in the frame "navbar." It compares the URL with that of the current page, with location.href, and when it is identical, assign the "grayStyle" descriptor.

Demonstration

© 2009-2012 Xul.fr