Removing the active class from a Bootstrap menu can be achieved by targeting the specific

I have successfully implemented a Bootstrap Menu by placing it in a separate header.html file and using the php include function to call that file on every page of my website. However, I am now trying to figure out how to dynamically change the active class based on the page that has been loaded.

<header class="header_area">
    <div class="main_menu">
        <nav class="navbar navbar-expand-lg navbar-light">
            <a class="navbar-brand" href="./index.php">
                <img src="./Images/Test Logo Image.png" width="35" height="35" alt="" loading="lazy">
              </a>
            <a class="navbar-brand Company_Text hidden-lg" href="./index.php">Dolphin Rubber Udyog</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <div class="mr-auto"></div>
              <ul class="navbar-nav">
                <li class="nav-item active">
                  <a class="nav-link" href="./index.php">Home<span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="./about.php">About Us</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="./products.php">Products</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="./contact.php">Contact Us</a>
                </li>
                </ul>
            </div>
          </nav>
    </div>
</header>

Answer №1

Per your request in the comments seeking assistance with the implementation I recommended, I don't have access to all of your code but I believe I can still provide help.

For illustration purposes, let's consider your about.php and contact.php files.

This is a potential structure:

About.php

<?php
    $pageName = "about";
    //Code to include your menu (include menu.php;)
    //Rest of your page code

Contact.php

<?php
    $pageName = "contact";
    //Code to include your menu (include menu.php;)
    //Rest of your page code

(I'm utilizing shorthand for if-else statements to keep your code concise. Reference: https://davidwalsh.name/php-ternary-examples)

Menu.php

<header class="header_area">
<div class="main_menu">
    <nav class="navbar navbar-expand-lg navbar-light">
        <a class="navbar-brand" href="./index.php">
            <img src="./Images/Test Logo Image.png" width="35" height="35" alt="" loading="lazy">
          </a>
        <a class="navbar-brand Company_Text hidden-lg" href="./index.php">Dolphin Rubber Udyog</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <div class="mr-auto"></div>
          <ul class="navbar-nav">
            <li class="nav-item active">
              <a class="nav-link <?php echo ($pageName == 'home') ? "active" : ""; ?>" href="./index.php">Home<span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item">
              <a class="nav-link <?php echo ($pageName == 'about') ? "active" : ""; ?>" href="./about.php">About Us</a>
            </li>
            <li class="nav-item">
              <a class="nav-link <?php echo ($pageName == 'products') ? "active" : ""; ?>" href="./products.php">Products</a>
            </li>
            <li class="nav-item">
              <a class="nav-link <?php echo ($pageName == 'contact') ? "active" : ""; ?>" href="./contact.php">Contact Us</a>
            </li>
            </ul>
        </div>
      </nav>
</div>

I'm using this snippet of code to determine whether the about page should be highlighted as active:

<?php echo ($pageName == 'about') ? "active" : ""; ?>

To summarize my approach:

I've assigned a specific $pageName variable to each page to define its unique name. In menu.php, I retrieve this variable (possible due to the use of include(), which seamlessly incorporates PHP code) and based on its value, dynamically add the active class to the respective menu item.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When Safari injects elements that were previously hidden with display:none, they remain visible

Using the JS library MagnificPopup, I implement popups on my website triggered by a "read more" button. This library moves the html to display it in a different location and then injects it back when the popup is closed. While this functionality works seam ...

Avoiding Backbone Routing Conflicts when Implementing CSS3 Targeting

I have implemented a CSS target to create some basic animation in my Backbone project. However, I am facing an issue where the method I am currently using adds a #banner to the URL, which Backbone tries to interpret as a route if users refresh the page aft ...

How can I extract text from a website without retaining number, dot, and alphabet bullets in the list?

I am currently using Python 2.7.8 for a project involving a website with text displayed in an ordered list format using ol tags. I need to extract the specific text items listed below: Coffee Tea Milk This is an example of the HTML code used on my websit ...

The jQuery.addClass() function seems to be malfunctioning

I'm encountering an issue with the addClass() method. For some reason, it's not functioning properly in this scenario: https://jsfiddle.net/0g1Lvk2j/20/ If you scroll to the end and close the last box by clicking on the orange box, the orange b ...

Can a Javascript file be concealed from view?

Imagine a scenario where the localhost root file is served an HTML file using the following code: app.get('/', (req, res) => res.sendfile('index.html')) Is it possible to include JavaScript files in the HTML document that are not a ...

I am seeking a way to conceal text in an HTML document using JavaScript when the browser window width is less than a specified amount, and reveal it when the window width exceeds that value

I attempted to use the window.screen.width method, but it appears that the script only runs once (upon page load). I am seeking a way for the code to run continuously. Below is my JavaScript snippet: var textinSelected = document.getElementById("se ...

Is it possible to dynamically adjust the width of table columns using CSS/LESS on a per-column basis?

In this scenario, the table's column width is determined by the number of columns present. For example, if there are 4 columns in the table, each column's width would be set to a maximum of 25% of the table's overall width. With 3 columns, t ...

Tips for achieving seamless scrolling with the combination of javascript and css

Looking for a solution to achieve smooth scrolling on an HTML page without using the #id_name to scroll to a specific div. Instead, I want to scroll to a particular point, such as having a button that scrolls down the webpage smoothly by 250px when press ...

Show only a cropped section of a resized image within a div

I have a script that calculates the best region of an image to display within a specific div size. This calculation is done in PHP and generates a JSON output like this: {"scale":1.34,"x1":502,"x2":822,"y1":178,"y2":578} The image in question has dimensi ...

Using style binding and ngStyle doesn't appear to be effective for setting a background image within a DIV element in Angular5

After facing difficulties in customizing the spacing of Angular material cards, I decided to create my own cards. However, during this process, I encountered an issue where I needed to set an image as a background inside a div. Despite trying various CSS ...

Is it appropriate for HTML5 Web Workers to utilize CORS for cross-origin requests?

As I was creating a hosted API that relies on web workers, I encountered an intriguing issue. I am looking for feedback from the community to help me with this. Even though my server has the necessary CORS headers in place to serve the worker JS files and ...

Prevent the navigation bar text from being truncated

The below code snippet: <div data-role="navbar"> <ul> <li><a href="#page_1" data-transition="none">Heading 1</a></li> <li><a href="#page_2" class="ui-btn-active ui-state-persist">Heading 2</a& ...

The slider components have an endless loop feature that only runs once before coming to a

I'm working on creating an infinite slider that loops continuously without the need for navigation buttons. Instead, I plan to allow users to control the slider using touch gestures (although this functionality is not yet implemented in the code snipp ...

What is the best way to allocate a larger size to one part of a flex div?

A div is used to insert information <div class="inputs"> <div class="content">@Html.TextBoxFor(model => invoices.ProductDesc, new { disabled = "disabled", @readonly = "readonly" })</div> <div class="content">@Html.TextBo ...

Tips for getting rid of the glowing effect on MUI slider thumbs when they are in focus

import * as React from "react"; import Box from "@mui/material/Box"; import Slider from "@mui/material/Slider"; function valuetext(value) { return `${value}°C`; } export default function RangeSlider() { const [value, se ...

Is there a way to verify if an element possesses a specific style, and if so, alter the style of a different element accordingly?

Could you assist me in achieving a similar effect as demonstrated below: I have two menus (http://osiyo-nur.uz/osiyo-nur.uz/test6/), one of which is initially invisible. When I hover over the first menu, the second menu becomes visible with an overlay eff ...

Keep label at the forefront once input field is completed

Is it possible to keep my label positioned on top of the input field even after filling in data? I attempted using the valid function in CSS, but did not achieve the desired functionality. .txt_field input { width: 100%; padding: 0 5px; height: 4 ...

Steps to position images and text side by side in a grid layout

Trying to create a grid layout with profile images and text aligned next to each other, but struggling with CSS. If anyone could provide some guidance, that would be greatly appreciated! Here is the HTML code snippet: <div class="col-sm-3" ...

Troubleshooting problem with divs overlapping in Internet Explorer 7

Check out this webpage: http://jsfiddle.net/aJNAw/1/ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta ...

Adjusting the size of content tags depending on their popularity

Currently, I am working on setting up a basic tagging system by following the database structure provided in this Stack Overflow post. My goal is to create a single page that showcases all the tags, with each tag being visually scaled based on its popular ...