David
David

Reputation: 1191

Make <li> active with includes using PHP and CSS

I use these files as base for my website:

The menu.php:

$p = $_GET['p'];

switch($p)
{
    case "home":
        $p = "page/home.php";
    break;

    case "customers":
        $p = "page/customers.php";
    break;

    default:
        $p = "page/home.php";
    break;
}

<ul id='nav'>

   <li>Title</li>
    <ul>
        <li class="nav active"><a href="?p=home">Home</a></li>
        <li><a href="?p=customers">Customers</a></li>
    </ul>
</ul>

The default.php:

<body>
 <div id='navcontainer'>
  <?php include ("menu.php"); ?>
 </div>

<div id='content'>
 <?php include ($p); ?>
</div>

The style.css:

#navcontainer {margin:0; padding:0; width:220px;float:left;}
#nav li {background:#36393D; color:#fff; padding:5px 3px 5px 20px; margin:4px;border-left:5px solid #3F4C6B;}
#nav ul li{display:block; padding:3px; background:#fff; color:#000;border:none; padding:3px 0 3px 30px;}
#nav ul li:hover, #nav ul li.active {background:#eee; cursor:pointer; border-left:5px solid #4096EE;padding:3px 0 3px 25px;}
#nav ul li a {text-decoration:none; color:#000;}

The home.php and all pages:

<p>Hello world!</p>

I wonder if it is possible to get my menu.php to switch class to nav activeon the <li> items based on what page is currently visited.

Any ideas?

Upvotes: 0

Views: 3750

Answers (3)

dstrong
dstrong

Reputation: 7

I could not get

$p = $_GET['p'];

to work. What worked for me was

$p = $_SERVER[REQUEST_URI];

Upvotes: 0

GrayB
GrayB

Reputation: 1000

Using just php, you can create an extra variable

<?php
  $p = $_GET['p'];
  $currentPageId = 0;

  switch($p)
  {
    case "home":
        $p = "page/home.php";
        $currentPageId = 1;    
    break;

    case "customers":
        $p = "page/customers.php";
        $currentPageId = 2;    
    break;

    default:
        $p = "page/home.php";
        $currentPageId = 1;    
    break;
  }
?>

<ul id='nav'>

   <li>Title</li>
    <ul>
        <li <?php if($currentPageId == 1) { echo 'class="nav active"'; } ?> ><a href="?p=home">Home</a></li>
        <li <?php if($currentPageId == 2) { echo 'class="nav active"'; } ?> ><a href="?p=customers">Customers</a></li>
    </ul>
</ul>

Upvotes: 4

Mateusz Rogulski
Mateusz Rogulski

Reputation: 7445

You can give some id in REQUEST and then add:

$id = $_GET['id']

then

<li <?php if($id == your_id){ echo "class='nav visited'";} ?> >

Upvotes: 3

Related Questions