JavaScript line beneath the navigation

I have implemented a small JavaScript code snippet to add a line under links on my website. Here is the code:

$("li").on("click", function() {
    $("li").removeClass("line");
    $(this).addClass("line");
  });
.line {
    border-bottom: 4px solid #555;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <ul class="nav justify-content-center">
    <li class="nav-item">
      <a class="nav-link active" href="javascript:void(0)">Active</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="javascript:void(0)">Link</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="javascript:void(0)">Link</a>
    </li>
    <li class="nav-item">
      <a class="nav-link disabled" href="javascript:void(0)">Disabled</a>
    </li>
  </ul>

As you can see, this code adds a line under the selected list item. However, the issue arises when it also adds lines to other lists on the page that I don't want. How can I modify the JavaScript to only add a line under items within the "nav" class?

Answer №1

Ensure to attach the click handler to the class class="nav-item" rather than the li, this way, it will only highlight and respond to clicks on an li with a specific class name such as 'nav-item`

$(".nav-item").on("click", function() {
  $(".nav-item").removeClass("line");
  $(this).addClass("line");
});
.line {
  border-bottom: 4px solid #555;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="nav justify-content-center">
  <li class="nav-item">
    <a class="nav-link active" href="javascript:void(0)">Active</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="javascript:void(0)">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="javascript:void(0)">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link disabled" href="javascript:void(0)">Disabled</a>
  </li>
</ul>

Answer №2

To achieve this functionality, follow these steps:

Be more specific with your event triggering by ensuring the click only targets a li element with the class nav-item.

If there are other li elements with the same class name, consider adding an additional class to specify which ones should trigger the events.

$("li.nav-item").on("click", function(){
  $("li.nav-item").removeClass("line");
  $(this).addClass("line");
});

Answer №3

$("#line-container li").on("click", function(){
$("#line-container li").removeClass("line");
$(this).addClass("line");
});
 <ul id="line-container" class="nav justify-content-center">
      <li class="nav-item">
        <a class="nav-link active" href="javascript:void(0)">Active</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="javascript:void(0)">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="javascript:void(0)">Link</a>
      </li>
      <li class="nav-item">
        <a class="nav-link disabled" href="javascript:void(0)">Disabled</a>
      </li>
 </ul>

You can encase the ul (or any other element) responsible for displaying the line with an 'Id' attribute and then target specific li elements using that id, as demonstrated above.

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

Tips for effectively loading data of a specific user or event into a bootstrap modal in Laravel using AJAX

I'm having some trouble loading Event data into my bootstrap modal in Laravel. This is all new to me as I'm just getting started with AJAX. Can someone please take a look at what I've done so far? Modal Template <div class="modal fa ...

Getting started with Tween JS on a three-dimensional cube in Three JS

I'm venturing into the world of Tween JS and attempting to create a basic animation that moves objects to the right using Tween. Here is the code snippet from my init function (utilizing Three JS): var geometry = new THREE.CylinderGeometry(200, 200, ...

h1 tag set for jQuery AJAX activation

Currently working on a website that heavily relies on ajax. Encountering an issue that hasn't been solved through online resources. Now, I'm sharing my function for fetching a page: function loadTemplate(name, replaceWholePage = true){ $.wh ...

How can we access parameters in ag-Grid's Angular 1 onFilterModified event?

Currently, I am incorporating grid options using the code snippet provided below: var gridOptions = { columnDefs: columnDefs, rowData: null, enableFilter: true, onFilterChanged: function() {console.log('onFilterChanged');}, onFilterModified: fun ...

What's the source of this undefined error and is there a way to eliminate it from the code?

After successfully filtering and reducing the data, I encountered an issue with undefined. I am trying to figure out what is causing this and how I can either remove it or make it visible on the screen without being invisible. You can also check the codes ...

Issue: Request from a different origin blocked

I encountered an issue while working on a web project using the PlanGrid API. I am receiving a cross-domain request block error. var apiKey="API KEY"; var password="PASSWORD"; $.ajax({ url: "https://io.plangrid.com/projects", xhrFields: { ...

Is there a way to use jQuery to enable multiple checkboxes without assigning individual IDs to each one?

I need help finding a way to efficiently select multiple checkboxes using jQuery without relying on individual ids. All of my checkboxes are organized in a consistent grouping, making it easier for me to target them collectively. To illustrate my issue, I ...

AngularJS $scope variable can be initialized only once using an HTTP GET request

I'm facing an issue with fetching data from an API in a separate AngularJS application. There's a button that triggers the retrieval of data from the API. Upon clicking, it executes the $scope.getApiData function, which is connected to $scope.pr ...

Arrange DIV elements sequentially with HTML, JQuery, and CSS

Live Demo: Live Demo HTML: <div class="target"> <img src="bg-clock.png" alt="jQuery" /> </div> <div class="target2"> <img src="bg-clock.png" alt="jQuery" /> </div> CSS: .target, .target2 { ...

Exploring Django's view field for efficient data rendering

Is it possible to display multiple views for a single page/template? For instance, imagine a website where users can submit movie reviews and read others' reviews as well. Now, I need to add an edit button to the review pages but only want the button ...

Tips on expanding the background beyond the boundaries of a parent container with a specific width limit

Could you please take a look at the code snippet below? I am dealing with a situation where I have a container with a fixed width, and inside that container, there are rows whose width exceeds that of the parent container. Some of these rows have a backgro ...

What is the process of integrating unique themes into a non-Wordpress website?

In the process of developing my website, I am using PHP7, HTML5, CSS3, JQuery, and JavaScript5 instead of WordPress. One feature that I want to incorporate is the ability for users to customize their theme beyond the default option. How can this be achie ...

What is the process for retrieving the values of response headers in JavaScript?

After receiving a response from Axios, I need to retrieve the values from the Response Header. https://i.sstatic.net/lEcWg.png In the image above, I am specifically looking to extract the value of Location which is found in the Response Header. Could you ...

Prevent the image from increasing in size when removing padding from the Bootstrap Col

Using Bootstrap 4 Beta 3, I have set up a col-4 | col-8 layout. The first column contains an image, while the second column should contain both an image and text side by side. Currently, I have split the second column into another row with two columns. I ...

What is the significance of using composability over the deprecated method in Reactjs Material-UI menuItems?

I have taken over a project that was built using an older version of react, and I am currently in the process of updating it. However, I encountered console errors right off the bat. Error : bundle.js:6263 Warning: The "menuItems" property of the "Left ...

JsPlumb: Incorrect endpoint drawn if the source `div` is a child of a `div` with `position:absolute`

My current setup involves two blue div elements connected by jsPlumb. You can view the setup here: https://jsfiddle.net/b6phv6dk/1/ The source div is nested within a third black div that is positioned 100px from the top using position: absolute;. It appe ...

What is the best way to position a full width input beside my div element?

Having a small challenge with my CSS/HTML code, I am trying to position a full-width input next to my div. This is my HTML : <div class="leftdiv"></div> <input type="text" id="title-input" placeholder="nothing"></div> And here is ...

Exploring the World of HTML and PHP

I've recently started learning HTML and PHP. After installing the XAMPP software on my Windows computer, I launched the Apache and MySQL servers and created an HTML file like the one below - however, the PHP code doesn't seem to be executing. Eve ...

Interact with a webpage element using Selenium

My goal is to extract information from the following page: I want to interact with each blue stats icon on the page (one for every match of the tournament). Below is the code I am using: from selenium import webdriver from selenium.webdriver.common.by im ...

How can you utilize the Array submission syntax within HTML coding?

I currently have numerous input fields within a form, and some of them are structured like this: <input name="agents[]" type="file" /> Additionally, imagine there is a plus button next to this field as shown below: <img src="plus.jpg" id="some_ ...