phphtml

If I want to mark as active page in the navigation menu in menu.php


I used 'include' php to separate header of my website. So, I can easily fix if I need to change the navigation menu part in the header, instead fixing more than 20 pages each.

My question is I like to add a class, 'current' in the one of navigation button. For example, if I am in 'Home' page, then I want to change font color of 'Home' button to red. If I move to 'Contact' page, I want 'Contact' button to be changed to red and want 'Home' button to normal color.

Since all navigation button codes are in the header.html. How can I add class 'current', so users can know which page they are looking at?


Solution

  • If you are using php then you can set it like this.

    1) Give class to each link

    <li class="home"><a href="home.php">Home</a></li>
    <li class="about"><a href="about.php">About</a></li>
    <li class="contact"><a href="contact.php">About</a></li>
    

    Note : Give filename & classname same (If filename is home.php then class for this menu is "home")

    2) In header.php use this code.

    <?php
    $class = basename($_SERVER['REQUEST_URI'], '.php?' . $_SERVER['QUERY_STRING']);
    /* This basename function returns filename from url. For example if url is http://www.example.com/home.php?id=15, then this will return "home" only. */
    ?>
    <script type="text/javascript" src="jquery.min.js"> <!-- Link your jquery library -->
    
    <script type="text/javascript">
    $(document).ready(function(){
       $(".<?php echo $class; ?>").addClass('current');
    });
    </script>