How to change Bootstrap 4.5 dropdown alignment based on screen size?

Viewed 516

I have a button in the navbar using the dropdown component with right-alignment, because the button is to the very far right in the navbar:

<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 dropdown-menu-right" 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>

Now I want to change the alignment for screens smaller than medium (md). Can Bootstrap 4.5 do this out of the box? I didn't find any hint...

Thanks

1 Answers

Indeed, there is no out-of-box way to do it. But we can use simple jQuery code, since we are using Bootstrap. Lats add to .dropdown-menu one more class .align-toggle, the unique one, for our script. And a jQuery code, which toggles Bootstrap classes dropdown-menu-right and dropdown-menu-left depends on window width.

assignDrpdownAlign(); // calling function on load

window.addEventListener('resize', () => {
  assignDrpdownAlign(); // calling function on resize
});

function assignDrpdownAlign() {
  if ($(window).width() < 768) { /* checking for bootstrap MD breakpoint */
    $('.align-toggle').removeClass('dropdown-menu-right').addClass('dropdown-menu-left');
  } else {
    $('.align-toggle').removeClass('dropdown-menu-left').addClass('dropdown-menu-right');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js"></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 align-toggle dropdown-menu-right" 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>

Related