Jump to content

add active state to the navigation menu with php


runeveryday

Recommended Posts

<div id="nav">
            <ul>
                <li class="item"><a href="/">Home</a>/</li>
                <li class="item"><a href="/one">one</a></li>
                <li class="item"><a href="/two>two</a></li>
                 <li class="item"><a href="/three">three</a></li>
           </ul>
<div>

i want to add class='active' to the a tags . when the menu is the current page. namely.when i on the home page. the a label is

 

<li class="item"><a href="/" class="active">Home</a>/</li>

.but the others a label are not have class="active". when i on the one page. it is is

 <li class="item"><a href="one" class="active">one</a>/</li>

.the others a label are not have class="active".

 

 

Do you have a variable defining what page you're on? I assume here $currentPage defines the current page.

<div id="nav">
            <ul>
                <li class="item"><a href="/"<?php if($currentPage == "home") echo ' class="active"'; ?>>Home</a>/</li>
                <li class="item"><a href="/one"<?php if($currentPage == "one") echo ' class="active"'; ?>>one</a></li>
                <li class="item"><a href="/two"<?php if($currentPage == "two") echo ' class="active"'; ?>>two</a></li>
                 <li class="item"><a href="/three"<?php if($currentPage == "three") echo ' class="active"'; ?>>three</a></li>
           </ul>
<div>

If you don't have a variable like this already you could extract it out of one of the $_SERVER variables

$currentPage = basename($_SERVER['REQUEST_URI']);

Of course, you'll have to have special cases like when the REQUEST_URI is just '/', $currentPage will be a blank string.

 

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.