Issue with mobile device view: BS custom dropdown toggle not functioning

Built a Bootstrap dropdown navbar with custom jQuery & CSS, but facing an issue with toggling submenu in Mobile devices.

See the code snippet below:

$('.dropdown').click(function() {
  $(this).children('.dm-lv1').toggleClass('show');
  e.preventDefault();
});

$('.dropdown-submenu').click(function() {
  $(this).children('.dm-lv2').toggleClass('show');
  e.preventDefault();
});
.dropdown-submenu {
  position: relative;
}

.dropdown-menu {
  top: 0;
  left: 100%;
  box-shadow: 0 0px 5px rgba(0, 0, 0, 0.4);
}

.dropdown-menu {
  top: 90%;
  padding: 0;
  border: 0;
  border-radius: 0;
  border-top: 2px solid #333;
  background: #eee;
}

.dropdown-item {
  padding: .5rem 1rem;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<nav class="navbar navbar-expand-lg navbar-light">
  <div class="container">
    <a class="navbar-brand" href="#">Brand</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavDropdown">
      <ul class="navbar-nav ml-auto">
        <li class="nav-item active"><a class="nav-link" href="#">Home</a></li>

        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Products
          </a>
             // Dropdown menu content 
          

        </li>
        <li class="nav-item active"><a class="nav-link" href="#">Clients</a></li>
        <li class="nav-item active"><a class="nav-link" href="#">News</a></li>
        <li class="nav-item active"><a class="nav-link" href="#">Contact US</a></li>
      </ul>
    </div>
  </div>
</nav>

Is there a way to toggle (open/close) this dropdown and submenu on click rather than hover?

Answer №1

To enhance your scripts functionality, simply add 'e' to the event parameters like so:

<script>
    $('.dropdown').hover(function (e) {
        $(this).children('.dm-lv1').toggleClass('show');
        e.preventDefault();
    });

    $('.dropdown-submenu').hover(function (e) {
        $(this).children('.dm-lv2').toggleClass('show');
        e.preventDefault();
    });
</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

I am facing some issues with the React ToDoList project

I'm a student trying to create a ToDoList using React. When I try to submit or remove a schedule, nothing happens and the lists are not updated as expected. However, if I type something in the submission box, it works! I can't seem to figure ou ...

Using BootstrapValidator for conditional validation

While utilizing the BootstrapValidator plugin for form validation, I encountered a specific issue. In my form, I have a "Phone" field and a "Mobile" field. If the user leaves both fields blank, I want to display a custom message prompting them to enter at ...

How can you center a webpage and make it occupy 60% of the screen?

I was attempting to design a website where the main content takes up 60% of the body. This is what I tried initially: body { align-items: center; text-align: left; justify-content: center; width: 60%; } Unfortunately, this approach did not work ...

The page refreshes automatically when the search icon is clicked, but the ajax method does not trigger the page reload

Whenever I click on the search-box <a>, the JavaScript is triggered but doesn't execute the ajax method filter_data_guide_specs(). Instead, the page automatically reloads and fails to read the JS code. HTML <div class="form-group"> < ...

Tips for troubleshooting the StaleElementReferenceError in selenium automation

Encountering the persistent issue of receiving the error message StaleElementReferenceError: stale element reference: element is not attached to the page document every time I attempt to extract the text from a page body using Selenium. Numerous attempts h ...

When attempting to use dynamic imports with `react-icons`, NextJS will import all necessary components and dependencies

My current task involves incorporating an Icon from the react-icons package into my project. However, when I attempt to do so using an import statement, the resulting bundle size looks like this: Route (pages) Size First Lo ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

The result of jQuery is an Object Object in a dynamic and user-friendly web application

Working on an application that requires the use of JQuery has brought up an issue with my functions related to sons and grandsons in the code below: When typing http://localhost:8080/fathers into my browser, I receive the following response: [{"id":1," ...

Tips for updating the css class for multiple DOM elements using jQuery

I am currently attempting to modify the class property of a specific DOM element (in this case, a label tag) using jQuery version 1.10.2. Here is the code snippet I have written: var MyNameSpace = MyNameSpace || {}; MyNameSpace.enableDisableLabels = (f ...

Show only child elements of a specific type within the parent div

Looking to identify divs with the class 'test' that contain only buttons in their child nodes. This is the HTML code that needs to be filtered. <div class="test"> <div> <button> <span>Button 1</span></butto ...

Sockets causing a blockage in the Express server

Encountering an issue while setting up an express server with Sockets (using the socketcluster-server module). After sending around 20 http requests, the express server gets blocked, leading to the Sockets (client) reporting a connection depletion. Has an ...

Can we separate city, state, and country data into individual input fields using Autocomplete and Geonames?

Currently, I have a single INPUT field set up to trigger the jQuery UI Autocomplete function, which pulls data from Geonames API. $( "#city_state_country" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "http ...

Utilizing jQuery's load method to insert content into a div

My goal is to dynamically load the contents from external HTML files into a div called rightcontent on my webpage using jQuery's load method. Initially, the rightcontent div is empty, but as users interact with links on the page, text should be loaded ...

Maintaining consistent text spacing within a div, regardless of its minimum height: a javascript solution

I'm developing a JavaScript feature for creating status posts on a webpage. Within the "compose a post" div, there is centered text that reads "enter your text here" (using contenteditable). The issue I am facing is that when a new line is entered in ...

Retrieve the ID of the button that was chosen

Hello, I have a card with 3 selectable buttons as described below. <ul class="nav nav-tabs border-0" role="tablist" id="FlightType" onclick="SelectedFlightType()"> <li cla ...

how to make a post request to an API using Next.js

I am attempting to make a request to the Exist API using next.js and the backend is in PHP. I am trying to send a post request (using Axios) with data and retrieve the response. How can I manage this API in my code? I have read that I need to include som ...

Timing feature utilized in a Web Application

My latest project involves developing a web-based testing application using CakePHP. Here's how it works: when a user starts a test, the exact start time is stored on the web server. Once the test is completed and the answers are submitted, the serve ...

Developing a server-side handler for jQuery file upload

I am currently working on integrating the blueimp jQuery-File-Upload component into my MVC application. Here is the code I have implemented so far: JavaScript: $('#fileupload').fileupload({ url: '@Url.Action("AddAttachment", "File")&a ...

Is it possible to disable the timeout for a single call using Axios?

I have set up an axios client instance in my application like this: const backendClient = axios.create({ baseURL: window['getConfig']?.url?.backend, httpsAgent: new https.Agent({ rejectUnauthorized: false }), timeout: window['getConfig ...

Is commenting required? Well, meteor!

I am currently developing a chat application using Meteor and I am facing an issue where I want to require users to type something before sending a message (to prevent spamming by hitting enter multiple times). Unfortunately, I am unsure of how to achieve ...