6

I would like to highlight active page in menu using php. The page is in static version only common files are called using include in php i.e header.php,footer.php,navigation.php

navigation.php

<div class="collapse navbar-collapse" id="navbar-collapse-1">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="index.php">Home</a></li>
                        <li><a href="contact-us.php">Contact</a></li>
                    </ul>
                </div>

index.php

<?php
// Including Files
include('includes/header.php');
include('includes/navigation.php');
?> Rest HTML code goes here
rakeshkumar
  • 91
  • 3
  • 8

5 Answers5

11

PHP

$activePage = basename($_SERVER['PHP_SELF'], ".php");

HTML

<ul class="nav navbar-nav">
      <li class="<?= ($activePage == 'index') ? 'active':''; ?>"><a href="index.php">Home</a></li>
      <li class="<?= ($activePage == 'contact-us') ? 'active':''; ?>"><a href="contact-us.php">Contact</a></li>
</ul>
Nadun Kulatunge
  • 1,567
  • 2
  • 20
  • 28
1

You should use conditional statement in each li class attribute in navigation.php file. Use the $_SERVER["PHP_SELF"] predefined variable, for example for Contact link:

<li class="<?php $_SERVER['PHP_SELF'] === '/contact-us.php' ? 'active' : '' ?>"><a href="contact-us.php">Contact</a></li>
1

You can just add proper classes in the every page's <li> element and then later highlight the corresponding page button with some CSS.

Code example:

navigation.php

<div class="collapse navbar-collapse" id="navbar-collapse-1">
    <ul class="nav navbar-nav">
        <li class="index"><a href="index.php">Home</a></li>
        <li class="contact"><a href="contact-us.php">Contact</a></li>
    </ul>
</div>

index.php

// after php includes
<head>
    .index {
        color:red;
    }
</head>

contact-us.php

// after php includes
<head>
    .contact {
        color:red;
    }
</head>

...and so on.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Anirudh Goel
  • 134
  • 3
  • 15
-1

you could use the following:

.active, .home:hover {
  background-color: #666;
  color: white;
}
<div class="collapse navbar-collapse" id="navbar-collapse-1">
        <ul class="nav navbar-nav">
           <li class="home active"><a href="index.php">Home</a></li>
           <li><a href="contact-us.php">Contact</a></li>
        </ul>
    </div>  
JamesBond
  • 312
  • 2
  • 17
-2

You give the links an ID like #activeHome and #activeContact.

<li><a href="index.php" id="activeHome">Home</a></li>




Then you change in the HTML you only load at Home for example the background.

<style>
    #activeHome {
        background:blue;
    }
</style>



On the page Contact the corresponding.

deEr.
  • 357
  • 3
  • 12