Navigation menu with collapsible horizontal sub-menu display toggle

I have set up a test page using Bootstrap 4.3.1 to create a menu bar with submenus. The menu should display a triangle pointer when hovered over, indicating the selection. The user should be able to move the mouse to the submenu bar to choose a submenu. When clicking on a menu with submenus, the submenu bar (along with the triangle pointer) should remain in place until a submenu or another top menu is selected. However, I am encountering an issue where the styles of the submenu are being altered when trying to maintain the hover selection by adding/removing classes. Can someone offer assistance with this problem?

Thanks in advance.

Below are two screenshots:

https://i.sstatic.net/HfmWt.png https://i.sstatic.net/pkriL.png Html:

  <nav class="navbar navbar-expand-md navbar-dark ">
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#menubar">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse" id="menubar">
                    <ul class="nav navbar-nav">
                        <li class="nav-item ">
                            <a class="nav-link" href="#">Menu1</a>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-link" data-toggle="dropdown" href="#">Menu2</a>
                            <ul class="dropdown-menu" role="menu">
                                <li><a href="#">Submenu1</a></li>
                                <li><a href="#">Submenu2</a></li>
                                <li><a href="#">Submenu3</a></li>
                              
                            </ul>
                        </li>
                      
                    </ul>
                </div>
            </nav>

css:

@media (max-width: 767px) {
    .navbar-collapse {
        background-color: #565149;
    }
}
#menubar ul {
    height: 44px;
    padding-top: 5px;
}
#menubar .nav-link {
    font-size: 14px;
    padding: 8px 50px 0 0 !important;
    color: white !important;
}
    #menubar .nav-link:focus,
    #menubar .nav-link:hover,
    #menubar .nav-link:visited {
        color: white !important;
    }
    #menubar .navbar{
        padding-left: 0 !important;
    }
.navbar.navbar-dark,
.navbar.navbar-light {
    height: 44px; 
    margin: 0 15%;
}

nav.navbar .navbar-nav li.nav-item.active:after{
    content: "";
    position: relative;
    margin-left: -31px;
    left: 50%;
    bottom: 15px;
    border-left: 6px solid transparent;
    border-right: 6px solid transparent;
    border-bottom: 6px solid white;
}
/*submenu*/
#menubar li.dropdown.show {
    position: static;
}
    #menubar li.dropdown.show .dropdown-menu {
        display: table;
        width: 100%;
        text-align: center;
        left: 0;
        right: 0;
        margin: 0;
    }

.dropdown-menu > li {
    display: table-cell;
    padding-top: 6px;
}
.dropdown-menu > li a{
    font-weight:600;
}
    .dropdown-menu > li a:hover {
        text-decoration: none;
    } 

js:

  $("#menubar li.dropdown>a.nav-link").hover(function () { $(this).closest("li").addClass("active show") },
            function () { $(this).closest("li").removeClass("active show") });

Answer №1

By incorporating additional JavaScript code, I have enhanced the management of the menubar/submenubar's state. While I acknowledge that this may not be the optimal solution, it effectively fulfills its purpose:

 var clicked = false;
        $("#menubar li.dropdown>a.nav-link").hover(function () {
            
            var val = $("#clickstatus").val() + "; hover:on;" + (clicked ? "clicked" : "not");
            $("#clickstatus").val(val);
            if (!clicked)
                $(this).closest("li").addClass("active show");
        },
            function () {
                var val = $("#clickstatus").val() + "; hover:off;" + (clicked ? "clicked" : "not");
                $("#clickstatus").val(val);
                if (!clicked)
                    $(this).closest("li").removeClass("active show");
            });

        $("#menubar li>a.nav-link").on("click", function (e) {
            e.preventDefault();
            e.stopPropagation();

            var $li = $(this).closest("li");
           
            if (!$li.hasClass("dropdown")) {
                clicked = false;
                $("#menubar li.dropdown").removeClass("active show");
                $("#menubar li.dropdown").data("show", false);
                $("#clickstatus").val("clicked=false; not a dropdown. remove active&show");
            } else {
                if ($li.data("show")) {
                    clicked = false;
                    $li.removeClass("active show");
                    $li.data("show", false);
                    $("#clickstatus").val("clicked=false; a dropdown. is active, remove self active&show");
                } else {
                    clicked = true;
                    $("#menubar li.dropdown").removeClass("active show");
                    $li.addClass("active show");
                    $li.data("show", true);
                    $("#clickstatus").val("clicked=true; a dropdown. not active, remove then add active&show");
                }
            }
        });

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

Understanding the most recent tweet using the most up-to-date Twitter API

My goal is to retrieve the latest tweet using the most recent version of Twitter's API and add it to a specific div on my website. Despite attempting the code below, I have not been successful. If anyone could provide guidance on how I can accomplish ...

Gather every hyperlink and input fields without utilizing jQuery

Is there a way to target all a and form elements without relying on jQuery? My end goal is to achieve the following functionality: document.querySelectorAll('a').forEach(element => { element.addEventListener('click', () => { ...

Challenges associated with utilizing img src in JavaScript

I am facing a simple issue. I have carInfo data retrieved from a JSON file, but I am struggling to correctly parse the img source stored in the variable $imgsrc instead of treating it as a string called "$imgsrc". This data needs to be appended to my HTML ...

Preventing an iframe from reloading when transferring it to a new parent using appendChild

I'm looking to relocate an iframe to a different parent element while maintaining the iframe's current state (including scroll position and any entered form data). Unfortunately, when I use appendChild() to move the iframe, it reloads and resets ...

Display information in a table format by utilizing local storage with jQuery

I have encountered two issues while printing data in my table. When pulling data from localStorage to display in the table, I am facing some challenges. The data is saved correctly in localStorage as per requirements. However, the problems arise during th ...

Retrieving Ajax Data Using C#

I am struggling to send data through Ajax to a C# file. Whenever I check the received data, it always comes back as null. Could there be an issue in my code? Javascript file $(".save").click(function () { var ss = "Helloo!"; $.ajax({ typ ...

Select options in Django based on previous selections

While there are numerous answers to this question, I am a newcomer to Django and struggle with implementing these solutions. My goal is to work with the following models: class Region(models.Model): name = models.CharField(max_length=255, verbose_nam ...

CSS animation: Final position once the vertical text has finished scrolling

I have designed a CSS-animated headline with a leading word and three vertically-scrolling/fading statements to complete the sentence, inspired by the style used on careers.google.com. The animation runs through three cycles and stops, leaving the third st ...

tips for revealing content in a div by sliding from right to left

I came across a fiddle that animates from bottom to top when the cursor hovers over it. Is there a way to modify it so that it animates from right to left on click, and then hides the content? After hiding the content, I would like to have a button that a ...

Encountering a Laravel 419 Error due to CSRF Token verification problem during Ajax request handling

I'm running into a Laravel 419 error when using Ajax and I'm unsure of the cause. I've read in other posts that it might be related to the csrf token, but since I don't have a form, I'm not sure how to resolve this issue. Here&ap ...

Utilizing Bootstrap-Vue for a personalized navigation bar drop-down feature - a step-by-step guide

Currently, I am working on a website still in its early development stages, which combines Django and Vue technologies and utilizes the Maisonette Bootstrap theme. The website contains both traditional Django-rendered templates and a Vue single-page applic ...

How can I automatically update the content of a specific Div element when the page is loading using the Ajax load() function

This is the HTML code I have: <body onload="fun1()"> <ul id="nav" class="nav" style="font-size:12px;"> <li><a href="#" id="m_blink" onclick="fun1()">Tab1</a></li> <li><a href="#" id="d_blink" onclick="f ...

What is the best way to attach functions to specific jQuery objects and exclude others?

Imagine having an unordered list <ul>: <ul class="products"> ... </ul> You want to use jQuery to select it and then add custom functions to that specific object. For instance, you wish to include an addProduct(productData) function ...

Positioning an Anchor Element on the Right Side of a Bootstrap 4 Grid

Having some trouble with grid positioning. My markup differs from the example below, but for clarity, I'm explaining my issue here. The button on the right side of the screen looks good initially, but when I resize the window, it starts moving around. ...

"Unraveling the serialize() data from an ajax request in PHP: A step

I want to transfer form data to my php using ajax, but I'm facing issues with retrieving it correctly in my php code Here's the Ajax call: $(document).ready(function(){ $('#submit_comm').submit(function(){ let id = 's ...

View / Conceal Unordered List depending on link selected

How can I dynamically show or hide UL elements based on the clicked link? Here is a JS Fiddle example: http://jsfiddle.net/zangief007/rj8g0yh4/1/ Below is the HTML code: <ul class="category-1 group"> <li class="name">JOHN Smithe QC</l ...

Uploading files using HTML 5, Ajax, and jQuery

I am attempting to utilize jQuery to upload a file by using the ajax POST method and sending the uploaded file to url:"/files/uploads" with the parameter file. To achieve this, I have set up the following input elements: <form id="fileUploadForm"> ...

Retrieving the chosen value when there is a change in the select tag

Building a shop and almost done, but struggling with allowing customers to change product quantities in the cart and update prices dynamically. I've created a select-tag with 10 options for choosing quantities. I'd like users to be able to click ...

I am faced with the puzzling situation where the value of my input type slider is displayed below the slider

I am currently working with HTML code that allows users to select a percentage using an input type range. Here is the code snippet I am using: <div class="container-fluid"> <div class="row"> <div class="c ...

SyntaxError: Identifier was not expected

I am currently working on a function that involves a table of rows with edit buttons. Whenever the edit button is clicked, the following function is called and I encounter this error: Uncaught SyntaxError: Unexpected identifier The error seems to be poin ...