Using JavaScript to trigger a bootstrap dropdown toggle

Working on a bootstrap 4 dropdown menu that expands when hovered over, the goal is to prevent the link from being followed on touch-enabled devices and instead toggle the dropdown. I have successfully disabled the link, but toggling the menu remains a challenge. Below are my attempts:

JS

var button = jQuery('.btn-dropdown-link');

if ('ontouchstart' in window) {
  button.click(function (e) {
    e.preventDefault();
    console.log('clicked / touched');
    jQuery('#dropdownMenuButton').dropdown('toggle'); // struggling with this part 
  });
}

HTML

<ul>
    <li class="btn dropdown" id="dropdownMenuButton" aria-haspopup="true" aria-expanded="false">
        <a class="btn btn-dropdown-link dropdown-toggle" href="/com">some link</a>
        <ul class="dropdown-menu" id="dropdownDonateMenu" aria-labelledby="dropdownMenuButton">
            <li><a href="#">example</a></li>
            <li><a href="#">example</a></li>
            <li><a href="#">example</a></li>
        </ul>
    </li>
</ul>

CSS

.dropdown:hover > .dropdown-menu {
  max-height: 500px;
  opacity: 1;
}

.dropdown .dropdown-menu {
  transition: all 0.3s;
  max-height: 0;
  display: block;
  overflow: hidden;
  opacity: 0;
  min-width: 100%;
}

Here's a live example on codeply.

If you know how to toggle the dropdown after using e.preventDefault(); to disable the link focusing method, your insights would be greatly appreciated.

Edit: JavaScript solutions are preferred.

Answer №1

To implement the :active state in CSS, you can place it alongside the :hover state code. In the HTML, all you need to do is delete the href attribute.

For example, in the CSS:

.dropdown::active > .dropdown-menu, .dropdown::active > .dropdown-menu {
  max-height: 500px;
  opacity: 1;
}

In the HTML, simply remove the unnecessary

Answer №2

To achieve this, you can utilize the classes d-**-none and d-**-block at the specific breakpoint where you want the content to be displayed.

.dropdown:hover>.dropdown-menu {
    display: block;
    width: fit-content;
}
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<ul class="navbar-nav ml-auto">
  <li class="nav-item dropdown" style="cursor:pointer">
    <a class="nav-link d-none d-sm-none d-md-none d-lg-block dropdown-toggle" id="navbarDropdown3" data-hover="dropdown" aria-haspopup="true" aria-expanded="false" href="/com">dropdown</a>
    <a class="nav-link d-lg-none dropdown-toggle" id="navbarDropdown3" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" href="/com">dropdown</a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdown3">
      <a class="dropdown-item" href="#">Action</a>
      <a class="dropdown-item" href="#">Another action</a>
      <div class="dropdown-divider"></div>
      <a class="dropdown-item" href="#">Something else here</a>
    </div>
  </li>
</ul>

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

Complete the modal window form

I'm currently facing an issue with populating a modal window form. To provide some context, when I click on a grid row to edit a user, I make an ajax call which fetches specific data related to that user. Here is the existing code snippet: <modal ...

Choose a particular component from a snippet of a view

I am facing challenges with implementing a JavaScript function in a partial view. My objective is to validate the email input and display a message based on the validation result. The email field is located inside a partial view that is dynamically loade ...

Struggling with a scrolling problem in Bootstrap 4 horizontal cards?

Recently, I utilized a bootstrap card to display an image with text below it. I opted for the card class because of its solid structure and to avoid excessive CSS styling to horizontally align div lists. I envisioned creating an image gallery with a horizo ...

Is it possible to save the video title as a variable using YTDL-core?

Is there a way to store the video title as a global variable in JavaScript? ytdl.getBasicInfo(videoURL, function(err, info) { console.log(info.title) }); I have been trying various methods but I am unable to successfully define a variable to hold the v ...

JavaScript: Changing the names of all object keys

As a beginner, I am struggling to rename some objects in my key using a map function. Below is my current array: "platforms": [ { "id": 6, "name": "PC (Microsoft Windows)" }, { "id": 11, "na ...

Identify whether the application is built with nextJS, react, or react-native

I'm currently developing a library for React applications and I anticipate that certain features will function differently depending on the environment. I am seeking a method to identify whether the current environment is a ReactJS application (creat ...

Steps for executing Mocha tests in a specified sequence

Background Currently, I am developing a Node.js program where I am creating test suites in Mocha using Chai and SinonJS. The program involves a core graphics module that manages access to a node-webgl context. Due to the nature of node-webgl, I want to i ...

How can I implement JavaScript validations specifically for elements that are currently visible on an HTML page when utilizing jQuery's .hide() and .show() functions?

Below is a snippet of my jQuery code. $("#firstBankDetail").hide(); $("#secondBankDetail").hide(); $("#thirdBankDetail").hide(); $("#fourthBankDetail").hide(); $("#noOfBankDetails").change(function(){ var value = $(this).val(); if(value == 0) { ...

Sending data using Ajax to the server-side code in ASP.NET

Struggling to successfully pass a series of values through Ajax to a code-behind method in order to insert the data into a database table. However, encountering issues where string variables are being received as empty strings and int variables as 0. The ...

Tap twice on Kendo Grid rows in the React Component

I am currently utilizing the React Grid component and I am in search of a solution to trigger a function when a row is double-clicked. While I have found a rowClick function that allows me to select a row or handle an onClick event: <Grid rowClick={e = ...

How can I convert a numerical value xxxx into the format xx/xx using AngularJS?

Is there a way to change the format of a four-digit number (or string) to display as xx/xx in AngularJS? I have a string consisting of four digits and I would like to learn how to format it in the XX/XX style. ...

Generate all conceivable combinations of elements found in the array

Looking to generate all possible combinations of elements (without repetition) from a given array and length. For example, with an array of: arr = ['a','b','c','d'] and a length of 3, the desired output would be a ...

What could be causing my dropdown menu to not appear when clicked?

I am trying to implement the functionality shown in the image. When the Settings button is clicked, a window should open allowing the user to navigate to their desired option. However, I am facing an issue where nothing happens when the button is clicked. ...

The CRUD application in MongoDB is functioning flawlessly within the vscode terminal, however, it is experiencing issues when trying to run it in separate terminals such as cmd

https://i.sstatic.net/OrRmg.png However, when using any independent terminal like Git bash or cmd, it is throwing an error https://i.sstatic.net/1GHxa.png https://i.sstatic.net/TIouh.png GitHub URL I am unsure why this error is occurring. Could you please ...

Attempting to retrieve dynamically generated input fields and cross-reference them with structured length .json data

In the process of developing code, I've implemented a for loop to dynamically generate HTML input fields based on the length of some data in a .json file. My goal is to use jQuery to compare the text entered in each input field with the corresponding ...

Step-by-Step Guide: Crafting a Non-Ajax Popup Chat Application

Recently, I created a unique dating website with a one-to-one chat feature similar to Facebook. However, I implemented this using the ajax technique and the setInterval function in JavaScript for regular updates. Upon reflection, I believe that this appr ...

- Determine if a div element is already using the Tooltipster plugin

I have been using the Tooltipster plugin from . Is there a way to check if a HTML element already has Tooltipster initialized? I ask because sometimes I need to update the text of the tooltip. To do this, I have to destroy the Tooltipster, change the tit ...

Adding a specialized loader to vue-loader causes issues when the template contains personalized elements

My vue2 component is structured as follows: <template> <p>Hello world</p> </template> <script> export default { name: 'Example' }; </script> <docs> Some documentation... </docs> In addition, I& ...

Generate an individualized rendering perspective

Hello, I am currently learning React and working on developing a Todo App. However, I have encountered an issue that has left me stuck. I need to figure out how to separate the value of [todos] into those marked as completed and pending. To-do List displ ...

Unraveling the Mystery of Passing Props in React.js

Currently taking an online course to learn React, I encountered a unique scenario where one property is attached to another property in this manner: this.props.property01(this.props.property02) The tutor briefly touched on this code line, leaving me quit ...