DYNAMIC MENU LINK COLOR CHANGE ON THE ACTIVE PAGE USING CSS - Jan 27th, 2015


When I accessed a web page I wanted to highlight the navigation menu entry corresponded to that page.

The only wrinkle was that I was pulling the navigation menu entries from a multi-record table called navigation_menu
that had a link text field called entry and another for the URL called URL. Further, I was including the navigation menu
code (contained in a file called _mainnavmenu.php) on all my pages with the following code:


<?php include ("_mainnavmenu.php"); ?>

That meant that I’d have to change the css value that I wanted to change on each page on the fly (my client wanted to
change the navigation menu entry text color for the active page).

With a lot of assistance from Claire Ryan, a developer on the Interactive Tools team, we came up with this simple and
elegant solution.

I created a class value in my CSS style sheet for the active class like this:


.active {
color: #FF0000;
}


My original mainnavmenu.php looked like this:


<ul >
<?php foreach ($navigation_menuRecords as $record): ?>
<li ><a class="special " href="<?php echo strtolower($record['url']) ?>"<?php echo strtoupper( $record['entry'] )
?></a></li>
<?php endforeach ?>
<li style="height:50px;">&nbsp;</li>
</ul>


I added the dynamic class by changing that code to:


<ul >
<?php foreach ($navigation_menuRecords as $record): ?>
<li ><a class="special " href="<?php echo strtolower($record['url']) ?>"><span class="<?php echo
stripos($_SERVER['SCRIPT_NAME'], $record['url']) !== false ? 'active' : 'inactive'; ?>"><?php echo strtoupper(
$record['entry'] ) ?></span></a></li>
<?php endforeach ?>
<li style="height:50px;">&nbsp;</li>
</ul>


The stripos looks for a (case insensitive) match for the $record [‘url’] value in the $_SERVER['SCRIPT_NAME'] (the
path to the file that is being accessed on the server) and if one is found it returns active, if not, it returns
inactive.

Since there is no class defined for the value “inactive”, the color is changed if the value of the class is
“active”..



The materials on this web site have been created for use with CMS Builder content management software. CMS Builder software is published and licensed for use by InteractiveTools.com. Please contact Interactive Tools for information on the downloading of the software or the purchasing of licenses.


Terms of Service