Highlighting current menu item if PHP include
Solution 1
You can also write the menu in PHP since you are already using PHP to load the menu simply run an if/else statement on the menu-items to check if the "href" in the link matches the current URL of the page and set the menu item to "active".
Solution 2
Make your menu.html
into menu.php
and within that file do something like
<ul class="menu">
<li <?php echo ($page == 'page1') ? 'class="current"' : '';?>> <a href="#">Page1</a> </li>
<li <?php echo ($page == 'page2') ? 'class="current"' : '';?>> <a href="#">Page2</a></li>
</ul>
That way in each page you include your menu.php
you can simply set the variable like so
<?php
$page = 'page1';
include('menu.php');
?>
Keep in mind that this is just an example since we don't know what your current code looks like
Solution 3
In raw php this should be like
<?php
$currentPage = ''; // should be accessed from $_SERVER
$cssMenu = array('home.html', 'about.html');
if(array_search($currentPage, $cssMenu)) $cssMenu[$currentPage] = 'active';
?>
<ul id="top-menu">
<li class="<?= $cssMenu['home.html'] ?>">Home</li>
<li class="<?= $cssMenu['about.html'] ?>">About</li>
</ul>
Solution 4
Since you can't modify classes and divs before the page loads, you'll have to use some sort of javascript/jquery/whatever to dynamically highlight the link after the page is loaded. This shouldn't be too difficult; you can have a bit of Javascript that looks through the menu div (assuming you're using divs) for an href
entry which matches the current page, and then add the proper css class to that specific tag.
benhowdle89
Consultant software engineer and advisor to companies building software products.
Updated on June 04, 2022Comments
-
benhowdle89 almost 2 years
If i make a menu nav in html and use PHP to include it in every page on my website, how do i go about highlighting the current page if all i can put on the page is include("menu.html");