Upon selecting a hyperlink, a dropdown menu appears

I encountered a similar issue as described in the post "Bootstrap 3 - Disapear the dropdown menu when i click in a link", but I am having trouble closing the drop-down submenus using the provided solution.

My goal is to have a submenu close when another one is clicked open, rather than all submenus remaining open at the same time. The HTML structure is nearly identical to the example shared in the mentioned post:

<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
    <li class="dropdown">
        <a href="#MainMenu" data-toggle="collapse" data-parent="#MainMenu" class="dropdown-toggle"><img src="img/ico_menu_off.png" /></a>
        <div id="MainMenu" class="dropdown-menu">
            <div class="list-group panel dropdown">
                <a href="#link1" class="list-group-item list-group-item-success" data-toggle="collapse" data-parent="#MainMenu">Links to Portals <i class="caret"></i></a>
                <div id="link1" class="collapse background-submenu">
                    <a href="#SubMenu1" class="list-group-item" data-toggle="collapse" data-parent="#SubMenu1">Portal 1 </a>
                    <a href="#SubMenu1" class="list-group-item" data-toggle="collapse" data-parent="#SubMenu1">Portal 2 </a>
                    <a href="#SubMenu1" class="list-group-item" data-toggle="collapse" data-parent="#SubMenu1">Portal 3 </a>
                    <a href="#SubMenu1" class="list-group-item" data-toggle="collapse" data-parent="#SubMenu1">Portal 4 </a>
                </div>
                <a href="#link2" class="list-group-item list-group-item-success" data-toggle="collapse" data-parent="#MainMenu">Links to Calculators <i class="caret"></i></a>
                <div id="link2" class="collapse background-submenu"></div>
                <a href="#link3" class="list-group-item list-group-item-success" data-toggle="collapse" data-parent="#MainMenu">Links to Tools <i class="caret"></i></a>
                <div id="link3" class="collapse background-submenu">
                    <a href="#SubMenu3" class="list-group-item" data-toggle="collapse" data-parent="#SubMenu3">Customer Credit OverView</a>
                </div>
            </div>
        </div>
    </li>
    <li><a id="btn-customersearch" ng-click="customerSearchClick();" href="#customerSearch"><img src="img/u2973_off.png" /></a></li>
    <li><a id="btn-customerhome" ng-click="homeClick();" href="#/"><img src="img/u2983_on.png" /></a></li>       
</ul>     

<ul class="nav navbar-nav navbar-right">
    <li class="navbar-manager">Sheldon Cooper</li>
    <li><a href="#"><img src="img/u2977.png" /></a></li>
    <li><a href="#"><img src="img/u2975.png" /></a></li>
    <li><a href="#"><img src="img/u2979.png" /></a></li>
    <li><a href="#"><img src="img/ico_closesession.png" /></a></li>
</ul>          
</div>

Despite trying different functions like the following:

//Hide the menu when you click everywhere on the page - Ocultar menu cuando se haga click fuera del mismo
        $(document).on('click', function (e) {
        //$(document).on("click", "body", function(e) {
            //Target => collapse('hide')
           if($("#MainMenu").hasClass('in')) {
               $("#MainMenu").collapse("hide");
           }
           //stop the code from bubbling up
           e.stopPropagation();
           e.preventDefault();     
        });
    //dropdown menu
        $(document).on("click", function() {
            $("#MainMenu>div>a").on('click', function(e){
            e.stopPropagation();
            var dest = $(this).attr('href');
            $(dest).collapse('toggle');
         });
        });

I am still unable to achieve the desired behavior of hiding an open submenu when another one is opened. Any insights on how to properly implement this functionality would be greatly appreciated.

Thank you

https://i.sstatic.net/deulX.png https://i.sstatic.net/VV7c5.png https://i.sstatic.net/TACqp.png

Answer №1

If I'm understanding your issue correctly, you would like one submenu to close when another submenu is clicked (or when it's already open). Here is the updated JavaScript code for this scenario:

// Hide the menu when clicking anywhere on the page
$(document).on('click', function(e) {
    if ($("#MainMenu").hasClass('in')) {
        $("#MainMenu").collapse("hide");
    }
    e.stopPropagation();
    e.preventDefault();
});

// Dropdown menu functionality
$(document).on("click", function() {
    $("#MainMenu>div>a").on('click', function(e) {
        e.stopPropagation();
        var dest = $(this).attr('href');
        $(dest).collapse('toggle');

        if ($('#MainMenu>div>a').not(this) && $('#MainMenu>div>a').next('div.in')) {
            $("#MainMenu>div>a").next('div').removeClass('in');
        }
    });
});

Answer №2

By utilizing the following script:

// Ensuring accordion collapses each time dropdown is displayed
$('.dropdown-accordion').on('show.bs.dropdown', function (event) {
  var accordion = $(this).find($(this).data('accordion'));
  accordion.find('.panel-collapse.in').collapse('hide');
});

// Preventing closure of dropdown when an accordion link is clicked
$('.dropdown-accordion').on('click', 'a[data-toggle="collapse"]', function (event) {
  event.preventDefault();
  event.stopPropagation();
  $($(this).data('parent')).find('.panel-collapse.in').collapse('hide');
  $($(this).attr('href')).collapse('show');
})

and this styling in CSS

.panel-default>.panel-heading {
    box-shadow: none;
}

.fake-panel-link{
    margin-top: 0;
    margin-bottom: 0;
    font-size: 16px;
    color: #333;
    padding-left: 15px;
}

.fake-panel-link a, .panel-body  a {
    color:inherit;
}

.panel-body {
    background-color: #40B369;
    color:#333;
}

Simply nest an accordion within your dropdown to achieve the desired setup. Keep building on your initial concept.

Check out the DEMO here

The functionality is effective, focusing now on enhancing the CSS for a polished finish.

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

Instructions on how to trigger a function after adding HTML content to the directive

When working with the viewBannerCtrl controller and using the "customTable" directive, I encountered an issue. I am unable to access the "VBC.bannerAlert()" function from the directive even though I tried appending the code to the directive. Confusingly, I ...

Styling nested lists with CSS

Looking to implement CSS to style a nested list like the one below: 1. item1 subitem subitem 2. item2 subitem subitem I am trying to customize the appearance of the numbers (either in bold or red color). Despite searching online, the solutio ...

Flexible design for your website content wrapper

When I display the content on my website, it sometimes overlaps the footer because the wrapper does not adjust its size based on the content. I set the height to an absolute value and now I need to find a more flexible option to prevent this issue. I' ...

"Troubleshooting issue: Why isn't jQuery interacting with JSON data properly

I just discovered .json files and I'm attempting to include a multiline string in a data value, but it doesn't seem to be working. I've experimented with using \n, \r, and \n\r but none of them are functioning properly wh ...

Stop vertical scrolling in a designated div container

I am dealing with a div that is overflowing, but the horizontal scroll bar is not visible. How can I prevent actual scrolling on the div when the user attempts to scroll using the mouse or arrow keys? Below is the code for this div and a snapshot <!- ...

Angular 11 project facing issues with Bootstrap 5 tooltip functionality

Embracing the power of Bootstrap 5.0.2 in an Angular 11 project, I included the following code: index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compa ...

Using Tailwind's media query functionality within ReactJS

I have a situation where I have a div containing an image within it. I am attempting to use media queries from the Tailwind CSS framework. <div className="flex"> <img src="/assets/logo.png" className="h-20 md:w-2" ...

Is it possible to convert this to a switch statement?

I am utilizing a code snippet to handle the response from an ajax request, which looks like this: success: function(results) { if(results.locations){ //do stuff here }else if(results.error){ //do stuff here }else if(results.mat ...

Is it possible to trigger an AJAX function automatically following the success of another AJAX function?

I am in the process of implementing a note system using procedural PHP and AJAX. This system should have the ability to display new notes without refreshing the page and load more notes dynamically without needing a full page refresh. Currently, each func ...

Achieving Perfect Alignment: Centering Logo and Icons Vertically in the First Row of the Footer

I'm currently working on a footer layout and struggling to align the elements as desired. My goal is to have the "Logo" and icons in the "icon-container" vertically centered in relation to the first line of text within the "text-container," rather tha ...

Using Objective-C to dynamically generate UITextViews and UIImageViews from HTML content

Being new to iOS application development, I am currently faced with the challenge of pulling data from a website using NSURLSessionDataTask, parsing the JSON response (which is in HTML format), and then displaying the extracted information in a view. My c ...

The Google Chart is failing to show up on the screen

I'm having trouble implementing a feature that involves selecting a region from a dropdown list and requesting rainfall data to display in a Google Chart. Unfortunately, I've encountered some issues with it. Could you please help me identify ...

What causes the website to malfunction when I refresh the page?

I utilized a Fuse template to construct my angular project. However, upon reloading the page, I encountered broken website elements. The error message displayed is as follows: Server Error 404 - File or directory not found. The resource you are looking fo ...

Utilize either an array or object within the edit.php file when working with Grocery CRUD

Here's a snippet of code I'm grappling with: public function render() { // Apply filters if necessary $this->applyFilters(); // Define Columns and Fields $columns = array('code', 'name', 'fname&apos ...

Tips for modifying the class of a span inline element using a javascript function

Looking for assistance in creating a password text box with an eye icon that toggles visibility. When the user clicks on the eye icon, it should change to a crossed-out eye icon and switch the input type to text. <div class="input-group show-hide-passw ...

Ajax dependent dropdown is failing to load properly on the live server

My dropdown menus for country, state, and city are chained to each other, where the state options depend on the selected country and the city options depend on the selected state. While this functionality works perfectly on my local server, it's not w ...

Performing a function call in Angular2 directly from an HTML element without the need for a load event or similar event

Being a beginner in Angular, I have encountered an issue that seems to require a javascript workaround which is not very elegant. I am dealing with a model that has an array property. I am using ngFor to generate HTML selection options based on this prope ...

Bootstrap HTML - Medium-Sized Device Recognized as Large on Registration

Encountering some troubles with Bootstrap's Grid system on various devices. According to documentation, column sizes are based on window size: Extra small 576px , Small >= 768px , Medium >= 992px , Large >=1200px However, a medium devic ...

Can a website trigger an alarm on a user's iPhone without their permission?

Even though I have limited experience with HTML, CSS, and Javascript, I am curious if it is possible to create a basic website that can trigger an alarm on the user's device by simply clicking a button. For example, imagine a scenario where a user is ...

What is causing the discrepancy in the images on these two websites?

Site 1: , and site 2: . It's interesting to note that the velop logo on site 2 appears larger than the one on . Upon inspecting the source code using firebug, the image dimensions were consistent at 240px by 62px. Why does their visual appearance diff ...