Highlight Active Navigation Link

5 posts by 3 authors in: Forums > CMS Builder
Last Post: March 19, 2013   (RSS)

Hi,

This is how I've done this on projects I've worked on:

<ul id="nav">
  <li <?php echo ($_SERVER['PHP_SELF'] == '/index.php')? 'class="selected"' : ''; ?> ><a href="index.php">Home</a></li>
  <li <?php echo ($_SERVER['PHP_SELF'] == '/product-list.php')? 'class="active"' : ''; ?> ><a href="product-list.php">Products</a></li>
  <li <?php echo ($_SERVER['PHP_SELF'] == '/services.php')? 'class="selected"' : ''; ?> ><a href="services.php">Services</a></li>
  <li <?php echo ($_SERVER['PHP_SELF'] == '/pricing.php')? 'class="selected"' : ''; ?> ><a href="pricing.php">Pricing</a></li>
  <li <?php echo ($_SERVER['PHP_SELF'] == '/team.php')? 'class="selected"' : ''; ?> ><a href="team.php">Team</a></li>
  <li <?php echo ($_SERVER['PHP_SELF'] == '/contact.php')? 'class="selected"' : ''; ?> ><a href="contact.php">Contact</a></li>
</ul>

This is just example code, so you'll need to make a few changes to get it to work on your site. 

The $SERVER['PHP_SELF'] variable should return the name of the current page that is loaded. You can use this to check if the page name is the same as the link, and display a class of selected if it is. 

Let me know if you have any questions.

Thanks!

Greg

Greg Thomas







PHP Programmer - interactivetools.com

Hey Greg!

I just wanted to say thanks for what you posted here.  It helped me figure out one of the issues I was having, described here: http://www.interactivetools.com/forum/forum-posts.php?Listing-Blog-Categories-in-various-ways-78599

Now hopefully, someone can help enlighten me on the other items.   :-)   Thanks again!

- Jeremy

---------------------------

Dwelling Productions

www.dwellingproductions.com

By benedict - March 19, 2013

Great - thanks Greg, works well. I only have one other question:

When a user selects "departments.php", the navigation highlights as it should. When they select one of the department records (e.g. Bakery which has a URL of departments-detail.php?Bakery-4) it does not highlight, obviously because the URL has changed.

My question is, can you and multiple (i.e. 4 or 5) urls to this line of code below. If so, do you know the correct format?:

<li><a <?php echo ($_SERVER['PHP_SELF'] == '/departments.php')? 'class="selected"' : ''; ?>href="departments.php">Departments</a></li>

By dwellingproductions - March 19, 2013 - edited: March 19, 2013

Hi benedict!

Actually, that was the same issue I was having.  I fixed it by using REQUEST_URI instead of PHP_SELF (which reads the full URL instead of just the page name).  For more info, you can see my post here: http://www.interactivetools.com/forum/forum-posts.php?postNum=2229923#post2229923

Hope that helps!  :-)

- Jeremy

---------------------------

Dwelling Productions

www.dwellingproductions.com