How to create a highlighted active class in Bootstrap 4 navbar

I recently embarked on a web programming project and I've hit a roadblock in getting my links to display as active on the navbar. Despite searching for similar issues and solutions, I haven't been able to resolve the problem.

Here is an excerpt of my code:

<div>
<hr>
    <nav class="container-fluid navbar navbar-expand-sm bg-dark navbar-dark" style="padding-left: 75px; margin-top: -16px;">
        <ul class="navbar-nav">
            <li class="active nav-item">
                <a class="nav-link active" style = "padding-left: 0px; color: white;" href="#">Most Popular</a>
            </li>
             <!-- Other list items -->
            <li class="nav-item">
                <a class="nav-link " style="padding-left: 480px; color: white; " href="#">Log in</a>
            </li>
        </ul>
    </nav>
</div>

Additionally, I attempted to implement the following JavaScript snippet that I came across, but it hasn't yielded any results:

$('.nav li').click(function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
})

As I am just beginning my journey with coding, any assistance in troubleshooting this issue would be greatly appreciated. Thank you in advance!

Answer №1

There seem to be a few issues...

  1. The selector $('.nav li') is not functioning properly as there is no .nav class in the markup. It should be changed to $('.navbar-nav .nav-link').
  2. The inline style style="color:white" on the links will override any changes made with the active class.
  3. There is no CSS defined for the active class, and by default Bootstrap's active class on navbar-dark is white. What color are you attempting to set?
  4. The active state should be applied to the nav-link instead of the li element.

.navbar-dark .nav-item > .nav-link.active  {
    color:white;
}

$('.navbar-nav .nav-link').click(function(){
    $('.navbar-nav .nav-link').removeClass('active');
    $(this).addClass('active');
})

See a demo here:

Answer №2

If your navigation bar contains relative links such as "/projects",

// To eliminate any existing active classes in the navbar
$(".navbar .nav-item.active").removeClass('active');
// Add an active class to the appropriate navbar item that corresponds with the window location
$('.navbar .nav-item a[href="' + location.pathname + '"]').closest('li').addClass('active');

Answer №3

Yes, of course! Here is the updated code to highlight the active navbar link, complete with explanations:

$(document).ready(function() {
  $('.nav-link').click(function() {
    // Remove 'active' class from all links
    $('.nav-link').removeClass('active');
    // Add 'active' class to the clicked link
    $(this).addClass('active');
  });
});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Active Navbar Link</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0d2dfdfc4c3c4c2d1c0f0859e829e82">[email protected]</a>/dist/css/bootstrap.min.css">
</head>
<body>
  <div>
    <hr>
    <nav class="container-fluid navbar navbar-expand-sm bg-dark navbar-dark" style="padding-left: 75px; margin-top: -16px;">
      <ul class="navbar-nav">
        <li class="nav-item active">  <a class="nav-link" href="#">Most Popular</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">News</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Sports</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Science</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Politics</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Economics</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Random</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" style="padding-left: 480px;" href="#">Log in</a>
        </li>
      </ul>
    </nav>
  </div>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="script.js"></script> </body>
</html>

Answer №4

// set active navigation item

// fetch current URL
var currentPage = window.location.href;

// remove 'active' class from all nav items
$(".navbar .nav-item").removeClass('active');

// add 'active' class to the navigation item whose link matches the current URL
$(".nav-item a[href='"+currentPage+"']").addClass('active');

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

The issue of excessive recursion in Typescript

Currently, I am in the process of learning Typescript while working on some exercises. While attempting to solve a particular problem, I encountered an error related to excessive recursion. This issue arises even though I created wrapper functions. About ...

What steps can I take to rearrange my return statement within an asynchronous function?

Imagine having a function that fetches data from a database. findById(id) { return Model.findById(id) } The goal is to rearrange the output from the user data in this format: { name: "Tom", age: 57 } To something like this: { message: ...

Using Swig template to evaluate a condition

I'm trying to achieve something similar using swig-template. var remId = $(this).attr('remId'); if (remId) { var end = remId.search('_'); var underscore = remId.slice(end, end + 1); var Id = remId.slice(end + 1, remId ...

How can I simultaneously add two elements to a single node or to a node that does not exist in the JSON file?

I thought this would be simple, but I'm struggling to find the answer... var crit = { 'webshopId': webshopId, 'type': 'product'} }; I need to include sku.regularPrice = { $gte : parameters.minPr ...

A curated collection saved in LocalStorage using React JS

I have implemented a LocalStorage feature to create a favorite list, but it only adds one item each time the page is reloaded. The items are retrieved from a JSON file. For a demonstration of how my code functions, check out this link: const [ storageIte ...

Issues with CSS Modules not applying styles in next.js 13 version

Employing next.js 13.1.1 along with /app Previously, I had been handling all of my styles using a global.css, however, I am now attempting to transition them into CSS Modules. Within my root layout.js, there is a Header component that is imported from ./ ...

Is it possible to dynamically create new input fields by starting their index from the highest number after deletion?

I am working on a feature where users can add new rows with unique IDs and names. Everything works well, but the issue arises when deleting a row other than the last one. Here is an example of my code: $("#add_row").on('click', addRow); funct ...

JSX Script issue: the input prompt is missing

Greetings! I am currently working on a script to export JSON files from Adobe Illustrator. // Custom function for exporting prefixed objects function exportPrefixedObjects(doc) { // User input for prefixes and reference points var prefixInput = prompt( ...

Changing the website address | Node.js | Express

Is there a way to redirect incoming requests to different endpoints depending on a query parameter in the request? For instance, http://localhost:9000/?category=xyz&param1=...&param2=... The category value can be any of [abc, ijk, pqr, xyz]. Gi ...

Is it possible to create a unique AJAX function for a button element within a table?

Using an ajax function, I am populating a table with data from a PHP file that returns JSON encoded data. Each row in the table includes data as well as three buttons for delete, edit, and save operations specific to that row. The issue arises when I atte ...

Adjust the hue of p-dropdown options depending on a Boolean condition

Looking to modify the background color of my primeng drop-down items based on a boolean value retrieved from an API and stored in an array named users. The users array consists of objects with 3 fields. The API response includes: users=[{user_name:john.do ...

Customizing the appearance and dimensions of JWPlayer Audio Player with percentage-based styling

I'm currently attempting to set up an audio embed using JWPlayer, following the instructions provided in this particular article. The article suggests setting it up with the following code: <div id="myElement">Loading the player...</div> ...

Cryptocurrency price tracker with sleek Bitcoin symbol and FontAwesome icons

My assignment involved creating a function that retrieves Bitcoin trades from a JSON URL, allows users to change the interval with buttons, uses fontawesome arrows to indicate rate changes (up/down/no change), and displays the data on a website. Everythin ...

When utilizing exit-hook with process.on('SIGTERM'), child_process spawn requires two control-c commands to exit properly

I have the following program running: const { spawn } = require("child_process"); const exitHook = require("exit-hook"); exitHook(() => { console.log("Leaving"); }); spawn("my-program", ["my-args"], { stdio: "inherit" }); // Long running server ...

Not quite sure about the best way to showcase the results // using JavaScript

My code is posted below. I am trying to achieve a functionality where, upon clicking the 'Calculate Price' button, the results showing the number of cars, type of cars, and their respective prices are displayed beneath the button. Despite this be ...

Is there a way to effortlessly append a slug to my URL in a Node.js platform?

Currently facing challenges with my templates. As I develop an e-commerce platform, I am using a json file containing product details to create cards for each product. Due to the large number of products, creating individual pages for each one is not feas ...

Translation of error messages for length validator in Symfony 4

After utilizing the Symfony website skeleton to kickstart a new project, I set up a fresh registration form following the straightforward Symfony tutorial: https://symfony.com/doc/current/doctrine/registration_form.html#registrationformtype In my twig.yam ...

Unable to reach the controller's scope from the directive

Below are the configurations for my application: angular.module('myApp', ['myApp.directives', 'myApp.controllers', 'myApp.services']); Here is the controller I am using: angular.module('myApp.controllers&apos ...

Creating a vertical collapsible navigation menu with Bootstrap 4

I'm currently utilizing Bootstrap 4 and attempting to display a straightforward vertical collapsible menu. <div class="row"> <div class="col-3"> <div id="accordion"> <div> <div id="ta ...

Unable to store web service response in the $scope object

I'm facing an issue with setting the result when receiving a websocket message. I have a controller that, upon clicking a button, triggers the getStops function. Within this function (getStops), I utilize a websocket connection to receive messages ...