jquerybootstrap-5

Bootstrap 5 dropdown position is wrong when opened programatically


I have a Bootstrap 5 dropdown, with this HTML:

<div class="dropdown">
<p class="dropdown-toggle" data-bs-toggle="dropdown">Your company</p>
<ul class="dropdown-menu">
<li id="name">Company Name</li>
..
<li id="email">Email<span class="fail">✗</span></li>
</ul>
</div>

There is a difference in the location of the dropdown depending on whether I open it programatically or by clicking the arrowhead.

bootstrap dropdown

The left image is the dropdown when clicking the arrowhead. The right image is the dropdown when opened programatically with this code:

$('#email').parent().show();

Why is the position lower when opened programatically?


Solution

  • Using $('#email').parent().show() merely sets display: block to show the element, which still adheres to the standard box model(margin, padding, border...). As documented, you should programmatically control the dropdown component by:

    const dropdownIns = new bootstrap.Dropdown($('.dropdown-toggle'));
    dropdownIns .show();