Hovering over the Bootstrap dropdown menu will result in it being closed

I have implemented a dropdown menu with a secondary dropdown inside it. By incorporating JQuery code, I have enabled the functionality to open and close both dropdowns when hovering.

As I hover over the primary dropdown labeled services and proceed to hover over service2, which is the secondary dropdown, I encounter an issue where the dropdown closes as I try to access the elements within it such as Service2 sub1 and Service2 sub2.

Below is the code snippet:

HTML:

<div class="navbar navbar-default navbar-static-top">
    <div class="container">
        <ul class="nav navbar-nav">
            <li class="dropdown">
                <a href="#" data-toggle="dropdown" class="dropdown-toggle">Services <b class="caret"></b></a>
                <ul class="dropdown-menu">
                    <li><a href="#">Service1</a></li>
                    <li role="presentation">
                    <a data-toggle="collapse" href="#collapse" class="sub-menu">
                        Service2 <b class="caret"></b>
                    </a></li>
                    <ul>
                    <div id="collapse" class="panel-collapse collapse">
                        <li role="presentation"><a href="#">Service2 sub1</a></li>
                        <li role="presentation"><a href="#">Service2 sub2</a></li>
                    </div>
                    </ul>
                </ul>
            </li> <!-- .dropdown -->
        </ul> <!-- .navbar-nav -->
    </div> <!-- .container -->
</div> <!-- .navbar -->    

JQuery:

$(document).ready(function() {

    //Stop propagation for the dropdown
    $(document).on('click', '.dropdown-menu', function (e) {
        e.stopPropagation();
    });

    //Hover function for the main menu 'Services'
    $(".dropdown").hover(
        function() {
        $('.dropdown-menu', this).stop().fadeIn("fast");
        $(this).addClass('active');
        },
        function() {
        $('.dropdown-menu', this).stop().fadeOut("fast");
        $(this).removeClass('active');
        }
    );

    //Hover function for the sub-menu `Services`
    $(".sub-menu").hover(
        function() {
        $('#collapse').removeClass('collapse').addClass('collapse in');
        },
        function() {
        $('#collapse').removeClass('collapse in').addClass('collapse');
        }
    );

});

Feel free to test the functionality using this live fiddle: https://jsfiddle.net/0ksz9tnL/

Answer №1

Let me start by mentioning that there is an issue with your HTML structure. You have nested a ul within another ul.

Take a look at the snippet below:

<ul class="dropdown-menu">
    <li><a href="#">Service1</a></li>
    <li role="presentation">
    <a data-toggle="collapse" href="#collapse" class="sub-menu">
        Service2 <b class="caret"></b>
    </a></li>
    <ul>

Furthermore, if you move the class sub-menu from

<a data-toggle="collapse" href="#collapse" class="sub-menu">
to its parent, everything functions correctly.

Check out the Working Demo below:

$(document).ready(function() {

  //Stop propagation for the dropdown
  $(document).on('click', '.dropdown-menu', function(e) {
    e.stopPropagation();
  });

  //On hovering over the main menu 'Services'
  $(".dropdown").hover(
    function() {
      $('.dropdown-menu', this).stop().fadeIn("fast");
      $(this).addClass('active');
    },
    function() {
      $('.dropdown-menu', this).stop().fadeOut("fast");
      $(this).removeClass('active');
    }
  );

  //On hovering over the sub-menu `Services`
  $(".sub-menu").hover(
    function() {
      $('#collapse').removeClass('collapse').addClass('collapse in');
    },
    function() {
      $('#collapse').removeClass('collapse in').addClass('collapse');
    }
  );

});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<div class="navbar navbar-default navbar-static-top">
  <div class="container">
    <ul class="nav navbar-nav">
      <li class="dropdown">
        <a href="#" data-toggle="dropdown" class="dropdown-toggle">Services <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Service1</a></li>
          <li role="presentation" class="sub-menu">
            <a data-toggle="collapse" href="#collapse">
              Service2 <b class="caret"></b>
            </a>
            <ul>
              <div id="collapse" class="panel-collapse collapse">
                <li role="presentation"><a href="#">Service2 sub1</a></li>
                <li role="presentation"><a href="#">Service2 sub2</a></li>
              </div>
            </ul>
          </li>
        </ul>
      </li> <!-- .dropdown -->
    </ul> <!-- .navbar-nav -->
  </div> <!-- .container -->
</div> <!-- .navbar -->

<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

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

When importing scss files in Bootstrap 4, the generated file may differ from the original one found on the official getbootstrap.com

I am utilizing node-sass for my current project. If you want to experiment, create a simple style.scss file with both versions (alpha6 and beta): @import "./node_modules/bootstrap/scss/bootstrap"; then enter the following command: node-sass style.scss ...

Is the click count feature malfunctioning?

My goal is to track every mouse click made by the user, so I created a function for this purpose. However, it seems that the function is only counting the first click. To store the count values, I have created a variable. <!DOCTYPE html PUBLIC "-//W3 ...

Convert PHP MySQL REQUESTED DATE to XML format and display it on an HTML page

I've been browsing tutorials throughout the day, but have been unsuccessful in finding exactly what I need. My goal is to save strings in MySQL such as: - Name - Location - Type - Price What I'm looking for is a way to extract specific data and ...

I possess a primary menu with several submenus, yet I am encountering difficulty accessing the submenus. My goal is to efficiently navigate and access the appropriate submenu within the main menu

I am facing an issue with my CSS where the sub menu is currently showing from the left side, but I would like it to slide up and down instead. .outer { width: 100%; text-align: center; background-color: Gray; padding-top: 20px; bord ...

What is preventing the input box from shrinking further?

I created a search box using CSS grid that is supposed to shrink when the page is resized. However, it doesn't seem to shrink as much as I expected it to. Here is how it appears when fully extended: https://i.stack.imgur.com/tPuCg.png And here is how ...

Difficulties encountered when trying to send emails on iPhone with HTML formatting and attachments

I'm attempting to send a JPG attachment along with a formatted HTML message using [picker setMessageBody:emailBody isHTML:YES]; as recommended by several forum posts. However, what I've noticed is that the resulting email's content varies d ...

Font Awesome icons displayed using the <i class="icon-ok"></i> markup are not styled correctly and do not respond to events in Chrome

I implemented Font-Awesome, an iconic font designed for use with Twitter Bootstrap. Here is the markup: <i class="icon-remove reset-preference-button"></i> And here is the CSS: .reset-preference-button { cursor: pointer; } For JavaScript f ...

Is the dragging behavior of a rotated image different than that of the original image when using CSS rotation?

While working on a CSS grid to showcase images rotated at 60 degrees for a diagonal view, I encountered an issue. I wanted users to have the ability to drag and drop images within the grid, but when they drag an image, it moves as if it weren't rotate ...

Displaying collapsible elements in the navbar changes the overall aesthetic of the navbar design

I am attempting to design a navbar that includes collapsible items, a logo, and a button that remains visible at all times. My intention is to have the collapsible items trigger button on the left, before the logo, and the always visible button on the righ ...

Why do my tablet media queries take precedence over mobile view media queries?

I've noticed that when I view my website on mobile devices, the tablet media queries always seem to override my mobile media queries. Can anyone explain why this is happening? Here is how I have set it up: /* X-Small devices (portrait phones, less t ...

I'm having trouble with Bootstrap 4 where my fixed navbar won't stay separate from my jumbotron

Currently working on a website and utilizing Bootstrap. Looking to keep my fixed navbar distinct from my jumbotron, but struggling to achieve separation between the two. Is there a method to accomplish this without directly modifying the CSS file? Here i ...

Tips for eliminating default classes from Mui Typography styling

I’ve been working on creating a Typography element and noticed some default MUI CSS classes added when debugging in the browser. I attempted to disable them by using empty arrays at the end of the sx prop, but it did not work as expected. In the image p ...

Flexbox or Bootstrap 4 Grid: Which is the Better Choice?

My form is structured as follows: <div class="row"> <div class="col"> <textarea name="comment" class='form-control' placeholder='Type new comment here..'></textarea> </div> <div clas ...

Delete the event handler if the original selector used to set up the handler is unknown

I need to remove an event handler from the element. The current handler is added by a third-party plugin, and I want to prevent its behavior. As far as I know, the functions off() and unbind() require the original selector to be used. The issue arises b ...

Design concept - Trigger an action upon clicking a checkbox within a table row

I've been working on implementing a selectable table using material design. I want to trigger an action when a checkbox in a table row is clicked, but my attempts with jQuery have not been successful. Here's the structure of my table: <table ...

Divide the data received from an AJAX request

After making my ajax request, I am facing an issue where two values are being returned as one when I retrieve them using "data". Javascript $(document).ready(function() { $.ajax({ type: 'POST', url: 'checkinfo.php', data: ...

Yii employs the use of quickdlgs to efficiently generate fresh entries within the CGrid view

Within my web application, I am attempting to implement an iframe button using quickdlgs to create new records. However, upon clicking the iframe button, instead of being directed to the 'create' webpage, I am presented with an empty iframe. Here ...

Ways to prevent the TAB key from automatically shifting focus to the next element after using scrollIntoView during page initialization in the Chrome browser

Encountering a strange issue specifically on the Chrome browser. After the page loads, I am using the scrollIntoView method in the ngAfterViewInit of an Angular component. When the page loads and scrolls to the element, everything appears to be functioning ...

Having issues with jQuery AJAX not functioning correctly in PHP environment?

Can someone explain how Ajax and jQuery work together? I'm new to both technologies and I want to use Ajax to delete a row in my index.php file. <head><link rel="stylesheet" type="text/css" href="css/style.css"></head> <h1&g ...

Can someone help me extract a specific portion and display the dimensions of the area?

In order for the mouse to create a selection range, simply release the mouse after making your selection. The selected area will display the values of width and height on both the X-axis and Y-axis in the designated fields. I am facing this issue and woul ...