Page 1 of 1

add active state to the navigation menu with php

Posted: Sat Apr 09, 2011 8:15 pm
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".

Re: add active state to the navigation menu with php

Posted: Mon Apr 11, 2011 12:36 pm
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