Tips for activating a dropdown in Bootstrap 4

I am currently working on a dropdown menu where I want to set an active state upon a click. The active class is added successfully when a link is clicked, but the issue arises when trying to remove the active class when another link is clicked. I only want one link to be active at a time.

https://i.sstatic.net/lR6gY.png

Jquery:

    $(document).ready(function () {

    $(document).click(function () {
        $('.link.activeLink').removeClass('activeLink')
    });

    $('.link').click(function (e) {
        $(this).toggleClass('activeLink');

        if ($(e.parentNode).hasClass('show')) {
            $('.activeLink').removeClass('activeLink');
        } 
    });

});

html:

  <li class="nav-item dropdown px-2 arrowDown">
                    <a class="nav-link link dropdown-toggle text-white paddingRightButton h-100 noPaddingRightLeft" href="#" data-toggle="dropdown" id="flatRoofingDropdown" role="button" aria-haspopup="true" aria-expanded="false">
                        Flat Roofing
                    </a>

Updated screenshot:

https://i.sstatic.net/nCRgu.png

After the dropdown closes, the link remains active, which is not the desired behavior.

Answer №1

To ensure only one link is active at a time, you need to first remove the class .active from all elements with the class .link before toggling the class .active on the link that was just clicked. It is important to also use stopPropagation() when a link is clicked to prevent the click event from bubbling up to the $(document).click() function.

$(document).ready(function() {
    $(document).click(function(e) {
      $('.link.activeLink').removeClass('activeLink')
    });

    $('.link').click(function(e) {
      e.stopPropagation();
      $('.link.activeLink').removeClass('activeLink')
      $(this).toggleClass('activeLink');
    });
});
.activeLink {
  color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="nav-item dropdown px-2 arrowDown">
    <a class="nav-link link dropdown-toggle text-white paddingRightButton h-100 noPaddingRightLeft" href="#" data-toggle="dropdown" id="flatRoofingDropdown" role="button" aria-haspopup="true" aria-expanded="false">
      Flat Roofing
    </a>
  </li>
  <li class="nav-item dropdown px-2 arrowDown">
    <a class="nav-link link dropdown-toggle text-white paddingRightButton h-100 noPaddingRightLeft" href="#" data-toggle="dropdown" id="flatRoofingDropdown" role="button" aria-haspopup="true" aria-expanded="false">
      Concrete Roof Tiles
    </a>
  </li>
</ul>

Answer №2

This is the resolved issue

  $(document).ready(function () {
    $(document).click(function (e) {
        $('.link.activeLink').removeClass('activeLink')
    });

    $('.link').click(function (e) {
        if ($(e.target).hasClass('activeLink')) {
            $(this).removeClass('activeLink');
        } else {
            $('.link.activeLink').removeClass('activeLink')
            $(this).toggleClass('activeLink');
        }         
    });
});

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

Encountered an unforeseen token "<" that is causing the server to return a 404 HTML page instead of the intended .js

I am currently developing a to-do list application using Node.js Express and EJS. In the app, I have implemented a filtering functionality with a URL path of "/filter/query". Based on the selected category (either "lists" or "lastupdated"), the app filters ...

Converting JSP email text into HTML format with Spring's formatting features

Currently, I am working on implementing an email service using Spring. Users have the ability to input the email subject and body in a form and send the email successfully. However, there is an issue where line breaks and tabs entered by the user are not b ...

Having trouble with the scrollbar appearance after updating Chrome?

I've encountered an issue with my code after the latest Chrome update. Is there a way to implement cross-browser styling for scrollbars? // Looking for Scrollbar Styling Solution const scrollbarStyle = { scrollbarColor: `${themeLayers.scrollBar[0 ...

Prevent scrolling with absolute positioning

Here's a snippet of my HTML pseudocode: <div> <VideoAnimation /> <div className="under-animation"> // a lot of content goes here </div> </div> The issue arises from using absolute positioning on th ...

Having trouble uploading a file to Laravel using the jQuery .post method?

Here is a snippet of my HTML code: <input type="file" class="form-control" name="file-name" id="file-id"> This is the JavaScript function that is meant to send the file to an API: var file = $('input#file-id').val(); $.post('my/url/ ...

Displaying a list in KoGrid is a feature that allows for easy

Utilizing KoGrid to bind data from a DataArray has been successful for displaying flat data. However, when dealing with an object member that is an array, the grid fails to display all the array members as a list. This issue arises because KoGrid struggles ...

css absolute positioning and setting the height of a repeating background

I am facing a challenge with a container that contains a repeating image and I want it to fill 100% of the available height. However, some inner divs have their :after pseudo elements absolutely positioned to achieve the desired borders, which is causing a ...

Attempting to showcase the text within an <a> element on a <canvas> element while ensuring there are no noticeable visual distinctions

Imagine having this snippet of code on a webpage: elit ac <a href="http://www.ducksanddos/bh.php" id='link'>Hello world!</a> nunc Now, picture wanting to replace the <a> tag with a <canvas> element that displays the same ...

retrieve the data-task-IDs from the rows within the table

I am currently working with a table that looks like this: <table id="tblTasks"> <thead> <tr> <th>Name</th> <th>Due</th> ...

Generate a Vue component that automatically wraps text dynamically

Challenge I am looking for a way to dynamically wrap selected plain text in a Vue component using the mouseUp event. For instance: <div> Hello World! </div> => <div> <Greeting/> World! </div> Potential Solution Approach ...

"Double socket event triggers within a short period of time

I'm currently developing a multiroom chat system using nodejs and socket.io. Below is the server-side script: socket.on('sendchat', function (data) { socket.username = data.name; // store the room name in the socket session for th ...

Add a new external link to the Jquery Mobile webpage

Hello, I'm primarily a designer and my programming skills are quite limited. I am attempting to embed an external page into my jQuery Mobile webpage using external links, which works well in Safari. However, the issue arises when I save the web app t ...

How to Create a DataTable Responsive Feature Where All Columns Collapse on Click, Except the Last One?

I am currently utilizing the DataTables library to generate a responsive table. I am aiming to create a feature where all columns in the DataTable can toggle between collapse and expand states when clicked, with the exception of the last column. Below is a ...

Using CSS to add color to the border of a shape

Is there a way to make only the top, shaped part of this polygon have a 2px blue outline? .graph { clip-path:polygon(0 78%, 9% 67%, 32% 77%, 56% 60%, 69% 30%, 88% 40%, 100% 20%, 100% 100%,0 100%); border:none; height:200px; width:100%; ...

trouble with overlapping mdl-sheet instances

Hey there! I have a quick question - Is it possible to have multiple mdl-sheets on one page that all share the same form? I tried implementing this but ended up with them overlapping each other instead of displaying next to each other from left to right. ...

Update Relative Links using JQuery or JavaScript

Currently, I am employed by a company that specializes in building websites using a specific platform. We have encountered an issue related to relative URLs within this platform. The platform exclusively utilizes relative URLs and I am looking for a way t ...

Utilize the success() callback in JQuery Ajax when handling a response that is null

Within my website application, users have the ability to invite other users to participate in their projects. By entering an email address, a request is sent to the server via post method to check if the user exists. If the user is found, it will return th ...

Elevate the block when encountering errors in HTML/CSS

Here is a picture of what I want, and below I will provide a more detailed description: Link to the image (I cannot paste it here) I am explaining the elements involved. There are three main components: 1) The topmost text "Bla bla bla bla" 2) The butt ...

Adjust the cell color for AgendaWeek view only in the full calendar

I am looking to modify the cell color of my full calendar specifically in AgendaWeek view. I have come across some solutions that only apply to basicWeek view. Can anyone provide assistance? Currently, the following event successfully changes the month vie ...

Create a list with interconnected input fields for duplication

I'm new to javascript and I have a question. I'm working on duplicating a list that has input fields for each option. The duplication is working fine, but the associated input fields are not showing up in the duplicated list. Additionally, I woul ...