add active state to the navigation menu with php

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
everydayrun
Forum Commoner
Posts: 51
Joined: Wed Jan 20, 2010 1:30 am

add active state to the navigation menu with php

Post by everydayrun »

Code: Select all

<div id="nav">
            <ul>
                <li class="item"><a href="/">Home</a>/</li>
                <li class="item"><a href="/one">one</a></li>
                <li class="item"><a href="/two>two</a></li>
                 <li class="item"><a href="/three">three</a></li>
           </ul>
<div>
i want to add class='active' to the a tags . when the menu is the current page. namely.when i on the home page. the a label is

Code: Select all

<li class="item"><a href="/" class="active">Home</a>/</li>
.but the others a label are not have class="active". when i on the one page. it is is

Code: Select all

 <li class="item"><a href="one" class="active">one</a>/</li>
.the others a label are not have class="active".
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: add active state to the navigation menu with php

Post by social_experiment »

Code: Select all

<?php
public function create_navigation() {
		if (!is_array($this->_links)) {
			echo 'The value needs to be an array';
		}
		else {
			foreach ($this->_links as $name => $target) {
				$fileNameLength = strlen($target);
				$extractedName = substr($_SERVER['PHP_SELF'], -($fileNameLength));
				if ($extractedName == $target) {
					echo "<span class=\"inactive\">$name</span>";
				}
				else {
					echo "<a href=\"$target\" title=\"$name\">$name</a>";
				}
			}	
		}  
	}
?>
If you use an array to create your links, you can use this function. Hth
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply