Make Twitter Bootstrap navbar link active

You need to ensure that you set the active class as part of the request response (as the page loads) and not before ie when the user clicks a link to request a different page.

First you need to determine which navlink should be set as active and then add the active class to the <li>. The code would look something like this

Tested by asker:

HTML within php file

Call a php function inline within the <li> markup passing in the links destination request uri

<ul class="nav">
    <li <?=echoActiveClassIfRequestMatches("home")?>>
        <a href="https://stackoverflow.com/questions/11813498/home.php">Search</a></li>
    <li <?=echoActiveClassIfRequestMatches("about")?>>
        <a href="about.php">About</a></li>
</ul>

PHP function

The php function simple needs to compare the passed in request uri and if it matches the current page being rendered output active class

<?php 

function echoActiveClassIfRequestMatches($requestUri)
{
    $current_file_name = basename($_SERVER['REQUEST_URI'], ".php");

    if ($current_file_name == $requestUri)
        echo 'class="active"';
}

?>

Leave a Comment