Jump to content

Help with Dynamic Menu Highlighting


seowebguy

Recommended Posts

Hi all, my first post here (except my intro post earlier today).

 

I looked for this in the Code Snippet section and didn't see it, and honestly I'm very much a noob at this (for now, at least) so I'm not quite sure what I'd look for anyway. I've got a decent grasp on HTML and CSS and very little PHP.

 

So here's what I need help with:  I wrote a simple PHP include so that all my main pages (including the index file) would all use the same file (navtabs.php) for their navigation tabs. But how do I make the code in navtabs.php dynamic for which button should be highlighted on the proper page?

 

Here is the code snippet for my navigation:

     <nav>
        <ul>
        	<li><a href="index.php" class="current">Home</a></li>
          <li><a href="page-two.php" >Page Two</a></li>
          <li><a href="page-three.php">Page Three</a></li>
          <li><a href="page-four.php">Page Four</a></li>
          <li class="last"><a href="page-five.php">Page Five</a></li>
        </ul>
      </nav>

 

Where class="current" is the highlighting attribute.  All my pages using the same include of this code show the Home tab highlighted?

 

Hoping someone has a simple fix for me. Thanks!

Link to comment
https://forums.phpfreaks.com/topic/225781-help-with-dynamic-menu-highlighting/
Share on other sites

before the navtabs.php is included, you'll need to set a variable to indicate which page is including the file. for instance, you could set $this_page = 0 for index, $this_page = 1 for page 1, $this_page = 2 for page 2, etc.,

 

then, in navtabs.php, you'll check to see whether each nav IS or IS NOT the current page. if it IS the current page, change the CSS class to the active class. if it IS NOT the current page, use the default/inactive CSS class.

 

example:

 

<?php

// Before the include, on page 2 for instance:
$this_page = 2;

// Inside the include file:
$active_class = " class='current'";
$default_class = '';

// Initialize all nav classes to default.
$nav0class = $nav1class = $nav2class = $nav3class = $nav4class = $nav5class = $default_class;

// Set class for selected page
${'nav'.$this_page.'class'} = $active_class;

// Display navigation in HTML
?>

<nav>
<ul>
	<li><a href="index.php"<?php echo $nav0class; ?>>Home</a></li>
  <li><a href="page-two.php"<?php echo $nav1class; ?>>Page Two</a></li>
  <li><a href="page-three.php"<?php echo $nav2class; ?>>Page Three</a></li>
  <li><a href="page-four.php"<?php echo $nav3class; ?>>Page Four</a></li>
  <li class="last"><a href="page-five.php"<?php echo $nav4class; ?>>Page Five</a></li>
</ul>
  </nav>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.