Thursday, 22 March 2012

Dynamic Menu Highlighting using php and CSS

The below example explains making a navigation menu that dynamically
highlights the currently displayed page using php and css

It is better to use a common navigation menu file on the site rather than repeating same code on all the pages.
The reason is that if the menu items change ,we can easily modified a single file rather than changing all the files.

In the navigation menu file (say navigationMenu.php) add the below code

   <div id="menu">
    $active[$currentPage] = " class=active";                //dont forget to put space infront of class
        <li <?php echo $active[1] ?>><a href="newfile1.php" id="index">HOME</a></li>
      <li <?php echo $active[2] ?>><a href="newfile2.php">CONTACT US</a></li>
        <li <?php echo $active[3] ?>><a href="newfile3.php">LINKS</a></li>
        <li <?php echo $active[4] ?>><a href="newfile4.php">TEAM</a></li>

In the CSS add

#menu a:hover, #menu .active a  {
    background-color: red;
    color: #5A5A5A;
    display: normal;
    font-size: 11px;

In the individual pages (say contactus.php) add

$currentPage = 2;
include 'index.php';

Demo : Clicking CONTACT US link

1 comment:

  1. This is just very good, thanks! I'm using it right now in