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

angular2 and ionic2 encounter issues when handling requests with observable and promises

I am attempting to trigger an action once a promise request has been resolved, but I'm having trouble figuring out how to achieve this. After doing some research, I learned that Ionic2 storage.get() returns a promise, and I would like to make an HTTP ...

Tips for passing parameters in the $http GET request to transmit information from a dropdown menu using AngularJS

In the modal window I have for creating a new object, there are three forms: 1) a simple input to create "Name"; 2) A dropdown with "Types"; 3) A dropdown with "Ids". The issue arises when trying to send the data after filling out all the forms. An error o ...

Is there a foolproof method to verify if a user truly has visibility of a div element?

When I search online, most solutions only consider the viewport and/or the first parent container that is scrollable when trying to determine if a div is visible. However, I am wondering if there is a foolproof method to check if a div is truly visible t ...

The ASP.NET Core framework features a static top menu bar and a fixed left-hand side menu for seamless navigation

I am currently utilizing ASP.NET Core 6, jQuery, and Bootstrap in my project. I have a specific screen layout where I want the left-hand side menu and the top menu to remain fixed in their positions, while only the input details section should be able to s ...

Guide to pulling and showcasing information from XML at 30-second intervals using JQUERY AJAX and HTML

Seeking assistance as a beginner. Looking to retrieve and showcase data (HTML / PHP page) from XML every 30 seconds. XML FILE : <MAINData> <LiveData> <Field no="1">ENG ODI</Field> <Field no="2">ENG</Field> ...

Adjust the position of the element by lifting it slightly

I am looking to adjust the positioning of the number "01 / 04" to match the layout shown in this image: Here is what I have accomplished so far: This is how the code structure looks like in vue js at the moment: <img id="theZoomImage" sizes="100vw" : ...

Utilizing PHP for Substituting URLs within HTML

Is there a way to use PHP to eliminate an entire <iframe> tag that contains the link abc.com? If I searched the following code for abc.com: ‹iframe src="http://abc.com/abcd.html"›‹/iframe› ‹iframe src="http://abc.com/lmno.html"›‹/ifr ...

Modify data in an array using Vuex

When working with my Vuex mutation, I am trying to replace an element in an array within the state. The code snippet below illustrates what I am attempting to do: UPDATE_MAILING(state, mailing) { let index = _.findIndex(state.mailings, {id: mailing.id ...

Encountering a bug that states "TypeError: Cannot read properties of null (reading 'useState')" while trying to use useState in a react application

I'm working on incorporating useState into my Next.js app, but I encountered an error as soon as I added the line of code to initialize useState. The popup error message reads: TypeError: Cannot read properties of null (reading 'useState') ...

Having trouble getting Calendly Webhooks to function in a node.js environment with ngrok?

Hello everyone, this is my first time seeking help on Stack Overflow so please bear with me if there are any flaws in my question. I recently started using the Calendly Teams version and decided to implement the Webhooks feature on a Node.js web applicati ...

Is it possible to implement Ajax functionality in JavaScript without using XMLhttp and connection the same socket for every request?

Can data on a page be communicated and updated without the need for reloading, all while avoiding the XMLHttpRequest object and using the same connection or socket for each request (without closing the connection each time)? ...

Leverage AJAX on the client-side for optimal performance while utilizing node.js

I am currently working on a simple nodejs application that displays HTML pages. Within this application, there are two buttons that are linked to JavaScript functions in separate files. One of the functions uses ajax, while the other does not. However, I a ...

Submitting the form with a target of _blank will result in the form being submitted on both a

I am currently working on a form that includes both a "Submit" button and a "Preview" button. While the submit button is functioning correctly, I am experiencing an issue with the Preview button. When clicked, it opens up a new page with the preview as in ...

Add a Page to Your Domain Name using the Text Input Box

I'm looking to create an input field that allows users to enter a text string, which will be added to a domain name when submitted, redirecting the user to a specific page. Here's how the process works: The user enters 'foo' into the ...

What steps should I take to host a Node.js application on a subdomain using an apache2 VPS?

Currently, I have a Node.js application that I would like to host on a subdomain using my VPS. The VPS is running apache2 and the Node.js app utilizes Express. Despite trying both Phusion and following this tutorial, I have been unsuccessful in getting i ...

Using JSON data to implement jQuery autocomplete feature

I've been stuck on this issue for hours and can't seem to find a solution. I have a PHP file that retrieves data from a table, converts it into JSON, and displays it as shown below: {"id":1,"name":"GR Gas","number":"1","gas":"0.02500000","diesel ...

Incorporate Facebook Friends into Your Website Using Graph API 2.5

In the midst of creating a website where users can connect with their Facebook friends, I encountered a challenge regarding utilizing apprequests. Unfortunately, this feature is only accessible to games from version 2.3 onwards. At present, my solution inv ...

Trouble arises when trying to open a new window using the Angular 8 CDK

I am attempting to open my component in a new window, similar to this example: https://stackblitz.com/edit/angular-open-window However, when the window opens, my component is not displayed and I receive the following error in the console: Error: Must pro ...

Compose an abbreviated version of the function

I am facing an issue with a function that involves calling out specific states with similar lines of code. Below is the function in question: DoThis(type) { if (type === 'a') { this.setState({ activeA: { display: 'block', opac ...

Retrieving data from Firebase query and displaying as an array of results

Currently utilizing the @react-native-firebase wrapper for interaction with Firebase's Firestore. Within my function, some querying to a specific collection is performed, with the expected result being an Array object containing each located document. ...