Jump to content

PHP adding active to nav menu with dropdown

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>



Then in my index.php:

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

 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

Share this post

Link to post
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:

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

Note where the php tags open and close.


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





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

Share this post

Link to post
Share on other sites

Join the conversation

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

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.