Resizable Column in Bootstrap Table

Resizable Column in Bootstrap Table
Code Snippet:Resizable bootstrap table
Author: Sohrab zia
Published: January 10, 2024
Last Updated: January 22, 2024
Downloads: 2,013
License: MIT
Edit Code online: View on CodePen
Read More

This Bootstrap code snippet helps you to create resizable table column functionality. It allows dragging and resizing table headers for better customization. This feature helps in adjusting column widths dynamically, enhancing table readability and user experience.

You can integrate this code into any Bootstrap project. It enhances table flexibility, enabling users to adjust column widths easily. This feature improves data presentation, ensuring a more organized and user-friendly layout.

How to Create Resizable Column In Bootstrap Table

1. First of all, include Bootstrap and necessary CSS links in your HTML file within the <head> section.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.2/css/bootstrap.min.css'>

2. Build your table structure within the HTML body, using the resizable-table class for the table. Customize the table structure and content as needed.

<div class="container mt-3">
  <table id="resizeMe" class="resizable-table table table-hover">
    <thead>
       <tr id="header-row">
        <th class="draggable-table" data-column="0">No.</th>
        <th class="draggable-table" data-column="1">First name</th>
        <th class="draggable-table" data-column="2">Last name</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>Andrea</td>
        <td>Ross</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Penelope</td>
        <td>Mills</td>
      </tr>
      <tr>
        <td>3</td>
        <td>Sarah</td>
        <td>Grant</td>
      </tr>
      <tr>
        <td>4</td>
        <td>Vanessa</td>
        <td>Roberts</td>
      </tr>
      <tr>
        <td>5</td>
        <td>Oliver</td>
        <td>Alsop</td>
      </tr>
      <tr>
        <td>6</td>
        <td>Jennifer</td>
        <td>Forsyth</td>
      </tr>
      <tr>
        <td>7</td>
        <td>Michelle</td>
        <td>King</td>
      </tr>
      <tr>
        <td>8</td>
        <td>Steven</td>
        <td>Kelly</td>
      </tr>
      <tr>
        <td>9</td>
        <td>Julian</td>
        <td>Ferguson</td>
      </tr>
      <tr>
        <td>10</td>
        <td>Chloe</td>
        <td>Ince</td>
      </tr>
    </tbody>
  </table>
</div>

3. Insert the following CSS code to make the table and its elements resizable. Adjust minimum width restrictions or other styles to suit your design.

.table {
  border-collapse: collapse;
  width: 100%;
}

.table,
.table th,
.table td {
  border: 1px solid #ccc;
}

.table th,
.table td {
  padding: 0.5rem;
}

.table th {
  position: relative;
   cursor: grab;
      user-select: none;
}   
   .table th:active {
      cursor: grabbing;
    }

.resizer {
  position: absolute;
  top: 0;
  right: 0;
  width: 5px;
  cursor: col-resize;
  user-select: none;
}

.resizer:hover,
.resizing {
  border-right: 2px solid blue;
}

.dragging {
  background-color: #f0f0f0;
}

4. Finally, add the JavaScript code to make the columns resizable and sortable. Ensure the table ID matches the JavaScript initialization code (#resizeMe).

document.addEventListener('DOMContentLoaded', function () {
  const makeTableResizableAndSortable = function (table) {
    const tableBody = table.querySelector('tbody');

    // Make rows sortable
    const rowsSortable = new Sortable(tableBody, {
      animation: 150,
    });

    // Make columns and table header cells draggable using interact.js
    const headers = table.querySelectorAll('th');
    interact(headers).draggable({
      // Enable both left and right edges for dragging
      edges: { left: true, right: true, bottom: false, top: false },
      listeners: {
        start(event) {
          const target = event.target;
          target.classList.add('dragging');
        },
        move(event) {
          const target = event.target;
          const dx = event.dx;
          target.style.transform = `translate(${dx}px)`;
        },
        end(event) {
          const target = event.target;
          target.style.transform = '';
          target.classList.remove('dragging');
        },
      },
    }).resizable({
      // Enable right edge for resizing
      edges: { right: true },
      restrictEdges: {
        outer: 'parent',
      },
      restrictSize: {
        min: { width: 50 },
      },
      listeners: {
        move(event) {
          const target = event.target;
          const width = parseFloat(target.style.width) || 0;
          target.style.width = width + event.dx + 'px';
        },
      },
    });
  };

  const tables = document.querySelectorAll('.resizable-table');
  tables.forEach(function (table) {
    makeTableResizableAndSortable(table);
  });
});



document.addEventListener('DOMContentLoaded', function () {
const createResizableTable = function (table) {
const cols = table.querySelectorAll('th');
[].forEach.call(cols, function (col) {
// Add a resizer element to the column
const resizer = document.createElement('div');
resizer.classList.add('resizer');


// Set the height
resizer.style.height = `${table.offsetHeight}px`;


col.appendChild(resizer);


createResizableColumn(col, resizer);
});
};


const createResizableColumn = function (col, resizer) {
let x = 0;
let w = 0;


const mouseDownHandler = function (e) {
x = e.clientX;


const styles = window.getComputedStyle(col);
w = parseInt(styles.width, 10);


document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);


resizer.classList.add('resizing');
};


const mouseMoveHandler = function (e) {
const dx = e.clientX - x;
col.style.width = `${w + dx}px`;
};


const mouseUpHandler = function () {
resizer.classList.remove('resizing');
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};


resizer.addEventListener('mousedown', mouseDownHandler);
};


createResizableTable(document.getElementById('resizeMe'));
});



//----------

Feel free to customize the table’s appearance and functionalities according to your project requirements.

That’s all! hopefully, you have successfully created a Resizable Table for your Bootstrap projects. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X