bootstrap dropdown in table code example

Example 1: create a dropdown in html bootstrap

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

Example 2: bootstrap dropdown in table

<div class='position-relative'>
...
  <td>
  <!-- Make sure position is static -->
  <div class="dropdown position-static actions d-inline-block">
      <button class="btn btn-light px-1 py-0 mt-1 dropdown-toggle actions-btn" type="button"
          id="table-action" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          <i class="mdi mdi-dots-horizontal"></i>
      </button>
      <div class="dropdown-menu" aria-labelledby="table-action">
          <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>
</td>
...
</div>

<script>
    $(function() {
        $('.actions').on('shown.bs.dropdown', function(e) {
            let menu = $(this).find('.dropdown-menu');
            let parent = $(this).parents('td').position().top;
            let top = $(this).position().top;
            let height = $(this).height();
            
            top = (top + parent);

            $("head").append('<style type="text/css" id="new-style"></style>');

            var newStyleElement = $("head").children('#new-style');
            newStyleElement.html('.dropdown-menu[x-placement^="left"],' +
                '.dropdown-menu[x-placement ^= "right"],' +
                '.dropdown-menu[x-placement ^= "top"] {' +
                'top:' + (top + height) + 'px !important;' +
                '}'
            );

            $('.actions').on('hide.bs.dropdown', function() {
                $("head").children('#new-style').remove();
            });
        })
    });

</script>

Tags:

Html Example