jean d'arme
jean d'arme

Reputation: 4353

Dropdown open on hover on desktop, but on click on mobile

I can't find a solution for Bootstrap 4 to have dropdown that open on hover (on desktop) and on click (when on mobile). All the solutions I found are using jQuery - anyone knows how to do it without that lib?

Upvotes: 1

Views: 1843

Answers (3)

tyan19
tyan19

Reputation: 13

You can do it in a simple way by using CSS like this:

@media (min-width: 992px) {
    .dropdown:hover>.dropdown-menu {
        display: block;
    }
}

Upvotes: 1

johannchopin
johannchopin

Reputation: 14873

You can easily achieve this effect by adding the class .show to the elements .dropdown-toggle and .dropdown-menu using pure JavaScript:

const dropdown = document.querySelector('.dropdown');
const dropdownToggle = document.querySelector('.dropdown .dropdown-toggle');
const dropdownMenu = document.querySelector('.dropdown .dropdown-menu');

['mouseover', 'click'].forEach(e => {
  dropdown.addEventListener(e, function() {
    dropdownToggle.classList.add("show");
    dropdownMenu.classList.add("show");
  });
});

dropdown.addEventListener('mouseout', function() {
  dropdownToggle.classList.remove("show");
  dropdownMenu.classList.remove("show");
});
<!-- CSS only -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

<!-- JS, Popper.js, and jQuery -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

<div class="dropdown">
  <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown button
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#">Action</a>
    <a class="dropdown-item" href="#">Another action</a>
    <a class="dropdown-item" href="#">Something else here</a>
  </div>
</div>

Upvotes: 1

Quentin H
Quentin H

Reputation: 121

Bootstrap 4 is using jQuery, you can't use the first without the second.

To do this, you can use two diffents event listener (three if you want to close the dropdown after hover) in JavaScript, like :

dropdownElement.addEventListener('click', function() {
    . . .
});
dropdownElement.addEventListener('mouseover', function() {
    . . .
});
dropdownElement.addEventListener('mouseout', function() {
    . . .
});

Upvotes: 0

Related Questions