Get Appointment

Blog Single

How to Highlight Active Pages in PHP Navigation Menus for Enhanced User Experience

  • Vfix Technology
  • 08 Jan 2024
  • php
  • 505 Views

Explanation

  1. $activePage Variable: Retrieves the current script's filename and removes the '.php' extension. It's used to identify the active page.

  2. Navbar Structure: The navigation menu comprises anchor tags (<a>) for different pages, each with a PHP snippet to conditionally add the "active" class based on the $activePage.

  3. Conditional Check: Each link checks if its associated page matches the $activePage. If true, it appends the "active" class to highlight the current page.

<?php
$activePage = basename($_SERVER['PHP_SELF']); // Gets the current script filename
$activePage = str_replace('.php', '', $activePage); // Removes the .php extension
?>

<!-- Navbar Start -->
<nav class="navbar navbar-expand-lg bg-white navbar-light shadow border-top border-5 border-primary sticky-top p-0">
    <a href="index.php" class="navbar-brand py-2 d-flex  px-lg-5">
        <img class="" src="img/logo.png" alt="">
    </a>
    <button type="button" class="navbar-toggler me-4" data-bs-toggle="collapse" data-bs-target="#navbarCollapse">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarCollapse">
        <div class="navbar-nav ms-auto p-4 p-lg-0">
            <a href="index.php" class="nav-item nav-link <?php if ($activePage === 'index') echo "active"; ?>">Home</a>
            <a href="about.php" class="nav-item nav-link <?php if ($activePage === 'about') echo "active"; ?>">About</a>
            <a href="services.php" class="nav-item nav-link <?php if ($activePage === 'services') echo "active"; ?>">Services</a>
            <a href="gallery.php" class="nav-item nav-link <?php if ($activePage === 'gallery') echo "active"; ?>">Gallery</a>
            <a href="contact.php" class="nav-item nav-link <?php if ($activePage === 'contact') echo "active"; ?>">Contact</a>
        </div>
        <h4 class="m-0 pe-lg-5 d-none d-lg-block"><i class="fa fa-headphones text-primary me-3"></i><?php echo $phone ?></h4>
    </div>
</nav>

Conclusion:

Highlighting active pages in a navigation menu using PHP is a simple yet effective way to improve user navigation experience. By applying this technique, users can easily identify their current location within the website. Implementing this code ensures a smoother and more intuitive browsing experience for your site's visitors.

Share :


+91 8447 525 204 Request Estimate