Activating list anchor upon click

I have a list that looks like this:

<!-- List -->
<ul class="nav nav-sm nav-tabs nav-vertical mb-4 steps-sampling">
  <li class="nav-item">
    <a class="nav-link active" id="link1" href="{{ url_for('overview') }}">
      <i class="bi-list-check nav-icon"></i>Overview
    </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="{{ url_for('upload') }}">
      <i class="bi-file-arrow-up nav-icon"></i> Upload file
    </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="{{ url_for('choose_numeric') }}">
      <i class="bi-sort-numeric-down nav-icon"></i> Choose the numeric column
    </a>
  </li>
</ul>

The first item in the list is initially marked as active. I want to change the active state when a different list element is clicked.

I attempted to do this with the following code:

$('.steps-sampling').on('click','a', function(){
   $(this).addClass('active').siblings().removeClass('active');
});

I also tried (adding an id to the anchor tag):

// Set the home menu item as active on initial load
$(".steps-sampling a#link1").addClass("active");

// Remove active class from all list items on click and add it to the clicked item
$("a").click(function(){
   $("a").removeClass("active");
    $(this).addClass("active");
});

Unfortunately, neither of these solutions worked.

I found the .active class for nav-link defined in the min.css file, making it difficult for me to customize it further.

.nav-link.active{border-color:#006673}

Since the Bootstrap template I am using does not seem to work well with adding active to the li element, I am unsure how to proceed. Any suggestions?

Answer №1

Upon exploring various options, I stumbled upon this solution that proved to be effective. The key lies in the fact that when the page refreshes, it reverts back to being active on the initial element:

    <script>
      $(document).ready(function() {
        $('a.active').removeClass('active');
        $('a[href="' + location.pathname + '"]').closest('a').addClass('active');
      });
    </script>

Answer №2

Your code is functioning properly, however there seems to be an issue with the styling.

Try using !important to override the default bootstrap style.

Check out the snippet below:

$('.steps-sampling').on('click','a', function(){
   $(this).addClass('active').siblings().removeClass('active');
});

// Set the home menu item as active on first load
$(".steps-sampling a#link1").addClass("active");

// Remove active class from all li's on click and add it to the clicked li
$("a").click(function(){
   $("a").removeClass("active");
    $(this).addClass("active");
});
.active {
  color:green !important;
  font-weight:bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94f6fbfbe0e7e0e6f5e4d4a1baa5baa7">[email protected]</a>/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="56343939222522243726166378677865">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet"/>
<!-- List -->
<ul class="nav nav-sm nav-tabs nav-vertical mb-4 steps-sampling">
  <li class="nav-item">
    <a class="nav-link active" id="link1" href="#">
      <i class="bi-list-check nav-icon"></i>Overview
    </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">
      <i class="bi-file-arrow-up nav-icon"></i> Upload file
    </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">
      <i class="bi-sort-numeric-down nav-icon"></i> Choose the numeric column
    </a>
  </li>
</ul>

Answer №3

Whenever you designate a function as a listener for an event, the event object is passed to the function once it is triggered. This object can be utilized to determine which element the user has clicked on:

$("a").click(function(evt){
    $("a").removeClass("active");
    $(evt.target).addClass("active");
});

Here's another method that achieves the same outcome in a more precise way:

$("a").on("click", function(evt){
    $("a").removeClass("active");
    $(evt.target).addClass("active");
});

In certain cases, depending on the content within the bound element, evt.target may refer to a different element than the one where the event was attached. It's important to ensure that you are targeting the correct element with the class styling:

$("a").on("click", function(evt){
    $("a").removeClass("active");

    let tgt=evt.target;
    if(!$(tgt).is("a")) tgt = $(tgt).closest("a");
    $(tgt).addClass("active");
});

Answer №4

Give this code a shot:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
.nav-item .nav-link {text-decoration : none;}
.nav-item .nav-link:hover{ border: 2px solid #006673 !important; }
.nav-item .nav-link.active{ border: 2px solid #006673 !important; }
</style>
<script>
$(document).ready(function(){
  $(document).on('click','.nav-link', function(){
     $('.nav-link').removeClass('active');
     $(this).addClass('active');
  });
});
</script>
</head>
<body>

<!-- List -->
<ul class="nav nav-sm nav-tabs nav-vertical mb-4 steps-sampling">
  <li class="nav-item">
    <a class="nav-link active" id="link1" href="#">
      <i class="bi-list-check nav-icon"></i>Overview
    </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">
      <i class="bi-file-arrow-up nav-icon"></i> Upload file
    </a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">
      <i class="bi-sort-numeric-down nav-icon"></i> Choose the numeric column
    </a>
  </li>
</ul>

</body>
</html>

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

Using JQuery to automatically set the default selection when toggling the visibility of a div

I currently have a script that toggles the visibility of a div when selected: $('.showSingle').click(function () { $('.targetDiv').hide(); $('.showSingle').removeClass('greenactive'); $(this).addCla ...

Using CSS to design a table-like structure with rows that span multiple columns

I am trying to generate a table dynamically using CSS and a JSON array. For example: In the code snippet provided, I have assigned a class of 'spannedrow' to span certain cells in the table, although the class is not defined yet. This is just ...

What could be causing my directive to not display the String I am trying to pass to it?

Currently attempting to create my second Angular directive, but encountering a frustrating issue. As a newcomer to Angular, I have been studying and referencing this insightful explanation as well as this helpful tutorial. However, despite my efforts, I am ...

Display full desktop version on mobile devices with minimized view and no need for horizontal scrolling

While it may seem unusual, my client has requested temporarily removing responsiveness from the site to view the desktop version on mobile. I initially tried removing the responsive meta tag, but encountered horizontal scrolls on the page. My goal is to di ...

The flow of Ajax execution halts once the initial calculation is completed

I have been developing an AJAX code that calculates fees. The code works well initially, but it stops functioning when I try to perform a second operation. <script> var weight = document.getElementById("weight").value; var ship_type = document.g ...

Encountering the 404 Page Not Found error upon refreshing the page while utilizing parallel routes

I'm currently developing a webapp dashboard using the latest version of Next.js 13 with app router. It features a dashboard and search bar at the top. I attempted to implement parallel routes. The @search folder contains the search bar and page.jsx wh ...

Tips on retrieving and showcasing information from various endpoints in React?

I am working with two different endpoints and I need to fetch data from both simultaneously in order to display it in one single element. For example, I want to show data from one table along with the corresponding name from another table if the product id ...

HTML forms default values preset

I need help with pre-setting the values of a dropdown menu and text box in an HTML form for my iPhone app. When the user taps a button, it opens a webview and I want to preset the dropdown menu and text field. Can someone guide me on how to achieve this? ...

Vertically Center Image in a Div

I have been struggling to center an image within a div, but all the usual methods like using margin: auto; do not seem to work. I have tried various popular techniques with no success. <style> /* Add a black background color to the top navigation ...

Mastering the Art of Implementing Jquery Contains Function

Exploring the jQuery website led me to the contains selector. $("div:contains('John')").css("text-decoration", "underline"); I am trying to figure out how to make this work with a dynamic value instead of hard-coding it. I attempted something l ...

The <form> element is giving me headaches in my JavaScript code

Trying to troubleshoot why my HTML pages render twice when I add a form with JavaScript. It seems like the page displays once with the script and again without it. Below is the basic HTML code: <form action="test.php" method="post"> <div class=" ...

Executing a pair of queries within the same table and integrating them within a unified route

How can I efficiently execute two queries on the same table in my project? I have been considering using promises, but my knowledge on them is limited. Even though I've researched about it, I am struggling to implement the correct structure. My main ...

Form on the internet with a following button

Currently working on a basic form: <tr> <td> <label for="FirstName">First Name <span class="req">*</span> </label> <br /> <input type="text" name="FirstName" id="FirstName" class="cat_textbox" ...

How can we create external labels for a polar chart in ng2-charts and chart.js, with a set position outside the circular rings?

Currently, I am working on creating a polar chart using Angular along with chart.js version 2.8.0 and ng2-charts version 2.3.0. In my implementation, I have utilized the chartjs-plugin-datalabels to show labels within the polar chart rings. However, this p ...

Conforming to HTML5 standards with ASP.Net DataList

I am currently working on updating my ASP.Net 4.0 website to comply as closely as possible with HTML5 specifications. One issue I have encountered is that whenever I use a DataList, it automatically adds the attribute cellspacing="0". I have tried various ...

Use JavaScript to upload a JSON file containing arrays into separate tabs

Looking for help with incorporating JSON data into an HTML template that features tabs and a gallery? Take a look at my setup below: <div class="tab"> <button class="tabLinks" onclick="openDiv(event, 'overview'); appendData()" id= ...

Managing empty functions as properties of an object in a React, Redux, and Typescript environment

I'm feeling a little uncertain about how to properly test my file when using an object with a function that returns void. Below are the details. type Pros={ studentid: StudentId pageId?: PageID closeForm: () => void } When it comes to creating ...

Pulling information from a database query to store it within a JavaScript variable

Using Ajax/JQuery, I successfully send the variable ($name) from page1.php to page2.php without refreshing the page. When the submit button is clicked, it sends me the var $name effectively. Additionally, in my JavaScript library for charts (AmCharts), the ...

React component state change in reverse

As I work on a simple login form component, I encountered an issue where clicking on the form should make it disappear and only display my JSON data. However, due to my limited experience with React state management, I seem to be achieving the opposite eff ...

How to properly handle file uploads and get the correct image path from Node Js (Express) to React Js?

Currently, I am working on my local system developing a file upload feature using node js. My project file structure looks like this: Project ..client .... source code of React App ..Server ....uploads ......avatar ........image.png ....index.js In this ...