Jump to content

PHP adding active to nav menu with dropdown


alphamoment

Recommended Posts

Hi I'm using PHP for my Navigation Menu, 

 

My navbar is in a file named "home.php" looks like this: 

    <ul class="nav navbar-nav navbar-right">

     <li><a href="?page=home">Home</a></li>
     <li><a href="?page=about">About</a></li>
     <li><a href="?page=services">Services</a></li>

       <li class="dropdown">
       <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
          <ul class="dropdown-menu">

             <li><a href="?page=service2">Service 2</a></li>
          </ul>
      </ul>

 

 
 

Then in my index.php:
 

 $page = $_GET['page']; 
 if (!isset($page)) {
    include('home.php');
 }
 if ($page == "home") { 
    include('home.php');
 }
 if ($page == "about") { 
    include('about.php');
 }
if ($page == "services") {
    include('services.php');
}
if ($page == "service2") {
include('service2.php');
}

 It all works how I want it to except for one thing; I'd like to add; 

<li class="active">

To the page that is currently being viewed. How can I do this? Thank you in advance. :)

Edited by alphamoment
Link to comment
Share on other sites

A really crude but easy way is to do the exact same thing that you've done for determining which file to include:

<?php
$page = $_GET['page'];
?>
<li<?php if($page == "home") { ?> class="active"<?php } ?>>
    <a href="?page=home">Home</a>
</li>

Note where the php tags open and close.

 

You'll just do that for each link, with the appropriate checks for each

 

Denno

 

Edit:

Actually I don't know if that would work the way I've written it.. It's been ages since I've done inline php like that.. You may have to do it like this:

 

<li<?php if($page == "home") { echo ' class="active"'; } ?>>
Edited by denno020
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.