Actually I tried different Javascript function to do this, they are note good to solve the problem.

Normally you can used Javascript function below to solve the problem:

一般可以用以下的js function来增加和删除已有的class来解决这个问题:

$(".nav a").on("click", function(){

Unfortunately, I found that the JS I used may conflict with Bootstrap JS. I can only click the link but the page didn’t go to the new link address. In the end I used HTML within php function to switch class from last "<li>" to current "<li>".


  • Call a php function inline within the markup passing in the links destination request url

markup passing in the links destination request url

<ul class="nav">
    <li <?=echoActiveClassIfRequestMatches("home")?>>
        <a href="home.php">Search</a></li>
    <li <?=echoActiveClassIfRequestMatches("about")?>>
        <a href="about.php">About</a></li>

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"';



comments powered by Disqus