bootstrap dropdown in datatable code example

Example: 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