Utilizing Bootstrap to emphasize the selected navbar item by adding the active class upon

I was attempting to emphasize the clicked navbar by adding an active class.

This is the code I tested:

<!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='icon' type='image/x-icon' href='static/images/logo.png'>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="#">[email protected]</a>/dist/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  <title>Demo</title>

</head>
<body>
  <script>
    $(document).ready(function () {
      $(".navbar-nav .nav-link").click(function (e) {
        e.preventDefault();
        $('.nav-item').removeClass('active');
        $(this).closest('.nav-item').addClass('active');
      });
    });
  </script>

  <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
      <div class="collapse navbar-collapse flex-grow-1 text-right" id="navNavbar" data-bs-toggle="collapse" data-bs-target=".navbar-collapse.show">
        
      <img style="width: 75px;" src='static/images/logo.png' class="rounded float-left"
        alt="logo">
      <ul class="navbar-nav ms-auto flex-nowrap">
        <li class="nav-item active">
          <a class="nav-link" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">check</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">About Us</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#">Contact</a>
        </li>
      </ul>

    </div>
  </nav>

  <script src="https://cdn.jsdelivr.net/npm/<a href="#">[email protected]</a>/dist/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
    crossorigin="anonymous"></script>
</body>

</html>

JQuery code:

  <script>
    $(document).ready(function () {
      $(".navbar-nav .nav-link").click(function (e) {
        e.preventDefault();
        $('.nav-item').removeClass('active');
        $(this).closest('.nav-item').addClass('active');
      });
    });
  </script>

Is there any issue with adding or removing the class?

Answer №1

$(function () {
    $(".navbar-nav .nav-link").on('click', function (e) {
        e.preventDefault();
        $(this).parent().siblings().removeClass('active');
        $(this).parent().addClass('active');
    });
});

Furthermore, ensure to include jQuery min JS in your HTML file.

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

Developing a webpage that navigates seamlessly without the hassle of constantly refreshing with

I am in the process of creating a website that is designed to run everything within the same file, but I am unsure about how to locate study materials for this project. For example: In a typical website scenario -> If I am on index.php and I click on ...

I have a `null` input value. Is there a way to compute this value in relation to a date

When the input is null, what can be done to calculate the value with date? https://i.stack.imgur.com/DmFsJ.png /* // ======================================================== * * * * * How To Calculate Input Value With Date When Input Is Null * * */ // ...

What is the best way to merge two JSON values with the help of jQuery?

Two JSON Objects are provided below: The first one is: [{ "id": 5001, "count": "0", "type": "None" }, { "id": 5002, "count": "0", "type": "Glazed" }, { "id": 5005, "count": "0", "type": "Sugar" }, { "id": 5003, ...

Encountering an issue when attempting to store image links in the database using PDO

One idea that I have is to create an image uploader system that sends the image to the 'upload' folder and saves the link to the database. I encountered errors in my 'images.php' file. Can anyone assist me with resolving these issues? ...

Upload several files sequentially in a form on a website using Selenium with Python

I need to automate the process of inputting multiple files from a folder into a website and running an online job for each file. Currently, I can only input one file at a time using this code snippet. from selenium import webdriver url = "http://www.exam ...

What is the best way to calculate the total sum of the first element in each index of an array when using ng

I am looking to calculate the sum of the first elements from all indexes of an array using ng-repeat in AngularJS. My goal is to declare a variable and increment its value with each iteration of ng-repeat, then display that variable at the end. Below is ...

Botched HTML and CSS layout

Looking at someone else's project and trying to improve the design without modifying the CSS. Struggling to figure out how to rearrange it in HTML. Any suggestions? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

How can you gather user data on a website without relying on a database and making it voluntary?

In order to streamline the process, the user should be able to send a preformatted email with the click of a button or have their data stored securely without leaving the site. The goal is to avoid the extra step of using a mailto: link, unless the email c ...

By default, Nuxt 2.15.7 is automatically installed when you create a new Nuxt app

I am looking to develop a Nuxt app (version 3) using Vue. However, when I run the command npm create nuxt-app@version mousa, it automatically installs Nuxt2. How can I install Nuxt3 instead with this command? ...

Matching the height of table cells with the background height

I'm struggling with the height of a table cell that contains a background image. The width of the cell is set to be 100% of the page's width, and the image's background-size is also set to 100%. This setup makes the background image scale to ...

How to Retrieve Upload Progress via HTTP Request in PHP

Is there a way to monitor the progress of file uploads by accessing the HTTP request in PHP? If so, how can this be achieved when uploading files into a MySQL database? require('../connect_db.php'); //Collect all necessary data $name = $dbc-> ...

Having trouble incorporating symbols with functionalities using HTML, CSS, and JS

I have implemented a table with three columns: "Action", "Question Subquestion/Text", and "Sort order". Additionally, I have incorporated a feature that allows for drag and drop functionality on the rows. Below is my code snippet: <!DOCTYPE html> &l ...

CSS menu with disappearing sub-menu on hover

I'm currently tackling a CSS-only menu project, but I'm struggling with keeping the sub-menu visible when moving away from the li element. The height should span 100% of the page, and the sub-menu should mirror the main menu, appearing to the ri ...

What is the reason behind the inconsistency of calling a function on click not always functioning properly in Chrome and FF, while working seamlessly in IE?

Consider a scenario where the code below is being used: <HTML> <HEAD> <SCRIPT> function myFunction(atlasTrackingURL) { var atlasURL = atlasTrackingURL; if (!atlasURL) return; //Creating a cache busting mechanism ...

Navigating to the end of the fixed-height table while inserting new elements

I'm experiencing an issue with a function that adds new items to a table with fixed height and overflow: auto set. When new items are added, the scroll should immediately go to the bottom of the table. Unfortunately, this is not happening as expected. ...

I am experiencing an issue where the CSS code is not appearing in the Chrome Debugger when I inspect an element

I recently wrote some CSS code to remove default browser styles: /* Box sizing rules */ *, *::before, *::after { box-sizing: border-box; } ​ /* Remove default padding */ ul[class], ol[class] { padding: 0; } ​ /* Remove default margin */ body, h ...

Arranging arrows in a horizontal alignment next to a column of images

Here is the div structure with two arrows positioned on top and bottom. I am trying to center the two arrows slightly towards the column of images. How can I achieve this? Link to a JSFiddle for reference: Fiddle I attempted the following CSS code, but ...

Tips for modifying the appearance of this input document

Hey there, I have this input element created in React: <span className="btn-file" type='button'> <div style={{display:'flex',justifyContent:'space-around'}}> <span style ...

Crafting a sleek arrow-style stepper with Bootstrap 5 breadcrumbs

I am attempting to create a stepper similar to the one showcased in this instance. To add color to the stepper, I utilized the text-bg-success or text-bg-primary classes on the breadcrumb-item as shown below. However, the spacing between the steps appear ...

What is the technique for rearranging columns to be at the top in Foundation for mobile devices?

On my desktop, I have a layout like this: [Column1 large-8] [Column2 large-4] For mobile view, I'd like it to be like this: [Column2 large-4] [Column1 large-8] Below is the code snippet I am working with: <div id="search-content" class="row ma ...