Unable to get the active class to work in Bootstrap 4 navbar

I'm struggling to make the active class in this specific navbar work on my website. I want the link to turn blue when I click on the current page. Being new to web development, I would really appreciate any help. Thank you in advance.

This is the navbar:

<div class="nav-scroller py-1 mb-2">
   <nav class="nav d-flex justify-content-between">
      <a class="active p-2 text-muted" href="#"><b> Business</b> </a>
      <a class="p-2 text-muted" href="#"><b> Design </b></a>
      <a class="p-2 text-muted" href="#"><b>Travel </b></a>
      <a class="p-2 text-muted" href="#"><b> Opinion </b></a>
   </nav>
</div>

Here is the javascript code:

$('.nav .p-2 .text-muted').click(function(){
   $('.nav .p-2 .text-muted').removeClass('active');
   $(this).addClass('active');
})

I have also utilized CSS to change the color of the current navbar page link to blue:

.nav  > .p-2.activate  {
   color:blue;
}

Answer №1

Take a look at the live demonstration:

$(document).ready(function(){
 $('nav a').click(function(){
   $('nav a').removeClass('active');
   $(this).addClass('active');
   let link=$(this).attr('href');
   window.location.href=link;
 });
});
.nav >a.active>b{
  color:blue;
}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">


<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
    
    <title>Hello, world!</title>
  </head>
  <body>
    <h1>Hello, world!</h1>

    
    
    <div class="nav-scroller py-1 mb-2">

   <nav class="nav d-flex justify-content-between">


      <a class="active p-2 text-muted" href="https://fonts.google.com"><b> Business</b> </a>
      <a class="p-2 text-muted" href="https://facebook.com"><b> Design </b></a>
      <a class="p-2 text-muted" href="google.com"><b>Travel </b></a>
      <a class="p-2 text-muted" href="#"><b> Opinion </b></a>

   </nav>

</div>

  </body>
</html>

Remember to pass section="yourpagename" from the server side to the frontend side.

You can now display the active link in two ways:

1) The first method involves using a ternary condition and adding a class to the anchor tag:

Here's an example of how to do it:

<a class="p-2 text-muted <% section=="Business"?'active':'' %>" href="#"><b> Business</b> </a>

2) The second way is to add the active class using jQuery:

 <a id="Business" class="p-2 text-muted" href="#"><b> Business</b> </a>

$(document).ready(function(){
    var section= "Business" . <--send value from server side same as link id
    $('#'+section).addClass('active');
});

Answer №2

Before anything else, it is important to note that your choice of selector is incorrect, so make sure to include the following:

$('.nav .p-2.text-muted').click(function(){
  $('.nav .p-2.text-muted').removeClass('active');
  $(this).addClass('active');
})

Also, pay attention to the css:

.nav > .p-2.active {
color:blue;
}

Answer №3

When working with JQuery, you included a class called active. However, in your css code, there is a class named activated. Make sure to update it to active

.nav > .p-2.active { color:blue; }

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

What is preventing me from installing react-router-transition on the 1.4.0 version?

$ npm install -S <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8dffe8eceef9a0ffe2f8f9e8ffa0f9ffece3fee4f9e4e2e3cdbca3b9a3bd">[email protected]</a> npm ERROR! code ERESOLVE npm ERROR! Unable to r ...

"My drop down button menus and background image seem to be experiencing some technical difficulties. Can someone help

I'm having trouble getting a drop-down menu to work with a reptile image as the background. When I remove the image, the drop-down works fine. I've checked for errors but can't seem to find any. Is it an issue with the code or maybe a typing ...

How come I'm facing difficulties in inserting data into Django Model instances?

Something odd is happening. I am making a post request from my current website, and though I receive the data on the backend, I'm unable to access the model's field using that data. This is what my Models.py looks like: class Records(models.Mode ...

Transforming a JavaScript script into a functional plugin

I've been working on converting my script into a plugin (code provided below), but I seem to be missing something. Can someone help me figure out where I went wrong? The page isn't showing any errors, so it's hard to pinpoint the issue. ;(f ...

Using regular expressions to swap out content within HTML tags

I am attempting to encrypt the text content within an HTML Document while keeping its layout intact. The text content is enclosed in pairs of tags, such as: < span style...>text_to_get< /span>. I aim to utilize Regex to extract (1) and then rep ...

Utilizing AngularJS to show content based on regular expressions using ng-show

With two images available, I need to display one image at a time based on an input regex pattern. Here is the code snippet: <input type="password" ng-model="password" placeholder="Enter Password"/> <img src="../close.png" ng-show="password != [ ...

The ListCreateAPIView in Django rest-framework fails to provide the complete file path as expected

I recently started utilizing Django rest-framework and encountered an issue with the JSON response returning only the path to the file stored on the server. Initially, I used the generics.ListCreateAPIView class. class PeopleList(generics.ListCreateAPIView ...

PHP loop that generates gaps between the buttons

My current challenge involves using a while loop to dynamically generate buttons based on the `outcomeId` count. However, I am facing an issue where the buttons created by the loop have gaps between them. <div class="outcomes"> <?php ...

Error in Webpack 5: Main module not found - Unable to locate './src'

When trying to build only Express and gql server-related files separately using webpack5, an error occurs during the process. ERROR in main Module not found: Error: Can't resolve './src' in '/Users/leedonghee/Dropbox/Project/observe ...

Encountering difficulties in sending the data to Firebase through the contact form

import React, { useState } from 'react' import styled from 'styled-components' import Title from '../Components/Title' import { InnerLayout, MainLayout } from '../Styles/Layout' import ...

Creating websites with HTML and CSS

I am trying to enhance the style of my paragraph by applying multiple attributes, such as font color and font type, using CSS. While applying a single attribute like p {color:green} works fine, I encounter errors when trying to apply more than one line of ...

What is the process for configuring environment variables in a React application?

I have set up my React app to run on http://localhost:3000, and now I am looking to configure environment variables for different environments such as development, production, staging, and local. These are the URLs for my React app in various environments ...

What is the best way to switch to the next track and pause the current track in dynamic content using JavaScript?

Is there a way to use javascript to play the next song and pause the currently playing song, especially when dealing with dynamic content that shares the same id and onClick value? How can we effectively manage dynamic content in javascript? https://i.sst ...

Guidelines for simultaneously modifying two dropdown select options

Is it possible to have one dropdown automatically change its value based on the selection made in another dropdown? For instance, if 'Value 1' is chosen from 'dropdown 1', can we set 'dropdown 2' to automatically display the ...

"The functionality of the Bootstrap4 tab panel is not working properly for switching

I am currently working on creating 4 tab panels using Bootstrap 4. My goal is for the tab contents to fade in when I click on them. However, I am facing an issue where nothing happens when I click on the other panels. Do you have any insights on why this ...

There will be no pop-up notification displayed if the product is already in the cart

When a product is added to the cart, the following code is used: addproduct(itemId) { this.showLoading = true this.$http.post('/shampoo', {'item': itemId}).then((response) => { swal({ title: "Success!", ...

Why does the variable in throw new exception print instead of the variable value being printed?

<div style="text-align: left;"> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> Name:<input type="text" name="name"><br> Age:<input type="text" name="age"> <br> ...

Is there a way to update a select box in JavaScript without refreshing the entire form?

Recently, I've encountered a challenge with using a form inside a modal. I need to dynamically add new fields to the select box and have them appear without reloading the entire page. Is this feasible? If so, could someone guide me on how to achieve t ...

Double-tap bug with Image Picker in Typescript React Native (non-expo)

Well, here’s the situation - some good news and some bad news. First, the good news is that the code below is functioning smoothly. Now, the not-so-good news is that I find myself having to select the image twice before it actually shows up on the clie ...