I am using a dynamic header for my page built in PHP and i am trying to apply the current CSS to the selected page. I can do this by defining class current in the html but this doesn't work with a dynamic header.
Here is my php header file what is wrong with my code. As far as I can tell the php statement should figure out the current page and apply the current css but it doesn't.
Thanks in advance for your help :). My website is: http://wonx.dk/phpintergrated/index.php
<?php
function get_current($title) {
if (strpos($_SERVER['REQUEST_URI'], $title) !== false)
echo 'class="current"';
}
?>
<a href="index.html"><img class="logo" src="img/logofinal.svg" alt="Devil Sheep Logo" /></a>
<label for="menuon">
<img src="img/menu.svg" alt="MENU"></label>
<input type="checkbox" id="menuon">
<nav>
<ul class="topmenu">
<li><a href="index.php" title="Home" >Home</a></li> <!--Sets the home tab to on meaning it is selected.-->
<li><a href="aboutme.php" title="About Me">About Me</a><!--Whitespace causes problems with display:inline-->
<ul class="submenu">
<li class="aboutdropdown"><a href="aboutme.php" title="About Me">About Me</a></li>
<li><a href="portfolio.php" title="Portfolio">Portfolio</a></li>
<li><a href="photogallery.php" title="Photo Gallery">Photo Gallery</a></li>
</ul>
</li>
<li><a href="recipe.php" title="Recipe">Recipe</a></li>
<li><a href="song.php" title="Song">Song</a></li>
<li><a href="cv.php" title="CV">CV</a></li>
<li><a href="experiments.php" title="Experiments">Experiments</a></li>
<li><a href="contact.php" title="Contact Me">Contact Me</a></li>
</ul>
</nav>
You have a finite number of menu items.
declare an array with all your menu items
$current['index.php'] = "";
.
.
.
$current['contact.php'] = "";
$temp = $current;
foreach($temp AS $key => $value)
{
if (strpos($_SERVER['REQUEST_URI'], $key) !== false)
$current[$key] = 'class="current"';
}
Now go to the html
<li <?php echo $current["index.php"]?>><a href="index.php" title="Home" >Home</a></li>
.
.
.
<li <?php echo $current["contact.php"]?>><a href="contact.php" title="Contact Me">Contact Me</a></li>
The . . . mean rinse and repeat.
Enjoy!
You have to put class on element itself, like:
<li><a href="index.php" title="Home" <?=get_current('home')?> >Home</a></li>
What happens if you want to specify another class to a link or somebody uses a CapiTalS within the title??
function get_current($title) {
$uri = strtolower($_SERVER['REQUEST_URI']);
if (strpos($uri, $title) !== false)
return 'current'; //-- Don't echo in a function, return something
}
And in your HTML
<li>
<a href="index.php" title="Home" class='<?php echo get_current('home');?>' >Home</a>
</li>