views:

18

answers:

1

I have an identical horizontal menu at the top of all of my pages, which I add using a PHP include() statement. In my stylesheet I want to have a class where if the user is on a particular page, the menu item corresponding to that page will have a different color. So, more or less:

#menu { background-color:blue; }

#menu .active { background-color:green; }

But, since the menu comes from the PHP include, it's always the same. How can I write some PHP or JavaScript that adds class="active" to the appropriate menu item for each page?

+1  A: 

When you include() a file, the included file has access to all the in-scope variables at the place where it gets included. You could easily set a variable to say which menu item should be active. A basic example might be something like this:

firstpage.php

<?php

$chosenMenu = 'page1';
include('menu.php');

menu.php

<div id="menu">
<?php
$menuItems = array(
    'page1'=>'firstpage.php',
    'page2'=>'secondpage.php',
    'page3'=>'lolcats.php'
);
foreach($menuItems as $key => $value) {
    echo '<a href="'.$value.'"';
    if (isset($chosenMenu) && $chosenMenu == $key) echo ' class="active"';
    echo '>';
}
?>
</div>

With this style, you can simply set a variable $chosenMenu before including your menu file, and you can control it from there.

zombat