Html css table resize

Resize columns of a table

Assume that we want to resize any column of the following table:

table id="resizeMe" class="table"> 
.
table>

Prepare the resizer

For each column, we insert a div element indicating that the associated column can be resized. The resizer element is positioned absolutely inside the column. The CSS styles for them would be as below:

.table th  
position: relative;
>
.resizer
/* Displayed at the right side of column */
position: absolute;
top: 0;
right: 0;
width: 5px;
cursor: col-resize;
user-select: none;
>

To create resizers and append them to columns, we have to query and loop over all columns:

// Query the table
const table = document.getElementById('resizeMe');

// Query all headers
const cols = table.querySelectorAll('th');

// Loop over them
[].forEach.call(cols, function (col)
// Create a resizer element
const resizer = document.createElement('div');
resizer.classList.add('resizer');

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

// Add a resizer element to the column
col.appendChild(resizer);

// Will be implemented in the next section
createResizableColumn(col, resizer);
>);

Handle the resizer’s events

We are going to implement a function, createResizableColumn , which accepts two parameters:

  • col that represents the table header
  • resizer that represents the resizer element within the column

In order to allow user to resize col , we have to handle three events:

  • mousedown on the resizer: Track the current position of mouse
  • mousemove on document : Calculate how far the mouse has been moved, and adjust the width of the column
  • mouseup on document : Remove the event handlers of document
const createResizableColumn = function (col, resizer)  
// Track the current position of mouse
let x = 0;
let w = 0;

const mouseDownHandler = function (e)
// Get the current mouse position
x = e.clientX;

// Calculate the current width of column
const styles = window.getComputedStyle(col);
w = parseInt(styles.width, 10);

// Attach listeners for document's events
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
>;

const mouseMoveHandler = function (e)
// Determine how far the mouse has been moved
const dx = e.clientX - x;

// Update the width of column
col.style.width = `$w + dx>px`;
>;

// When user releases the mouse, remove the existing event listeners
const mouseUpHandler = function ()
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
>;

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

Highlight the resizer

We can improve the user experience a little bit. When user hovers or clicks on the resizer, it can be hightlighted. To demonstrate the idea in the most simple way, we add a solid border to the :hover selector:

.resizer:hover,
.resizing

border-right: 2px solid blue;
>

The resizing class is added to the resizer while user clicks and drags the resizer:

const mouseDownHandler = function(e)  
.
resizer.classList.add('resizing');
>;

const mouseUpHandler = function()
.
resizer.classList.remove('resizing');
>;

Источник

How to make html table columns resizable?

There is guide here. It uses some jQuery, but nothing that can’t be replaced with simple vanilla JavaScript.

2 Answers 2

The resize property does not work with table. That’s why you need to put a div inside the table th and td , then resize it.

 
one
two
three
four
five
six
seven
eight
nine

if you want to know the new width, then you need to use jquery and get width of the div, because new width is not defined

This does not work for IE 11. Nor does it work for Edge. I suspect that both fail due to lack of support for CSS resize .

Here is some well written sample code for resizeable columns: https://www.exeideas.com/2021/11/resizable-columns-of-table-javascript.html It is different from putting div to every table field, it has much more readable resizable table as result.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to make html table columns resizable?

mouseup on document: Remove the event handlers of document,mousemove on document: Calculate how far the mouse has been moved, and adjust the width of the column,mousedown on the resizer: Track the current position of mouse,resizer that represents the resizer element within the column

Answer by Quinton Hess

 
one
two
three
four
five
six
seven
eight
nine

Answer by Eden McKinney

Re-sizeable Table demo 4, hover effect:,Re-sizeable Table demo 3, red color removed:,Re-sizeable Table preview, the table width is 100%:,Visit HTML table resizer demo page to download the minified version of «Table Resizer» script.

Create a table and style it

 * table td,th table,th,td 
Size File
10Mb C:\Users\BrainBell\Desktop\Empty\abc.txt

The following code will select all tables and pass them to resizableGrid function.

var tables = document.getElementsByTagName('table'); for (var i=0; i

You can change the code If you don’t want to select all tables. For example, to select a single table by id:

var table = document.getElementById('tableId'); resizableGrid(table);

Next, we’ll create the resizableGrid which retrieves the very first row of the table and store all td elements to cols variable using row.children .

function resizableGrid(table) < var row = table.getElementsByTagName('tr')[0], cols = row ? row.children : undefined; if (!cols) return;

We’ll make a div for each column as column selector using createDiv function and pass this div to setListeners function for adding some mouse events listeners.

The createDiv function makes a div with absolute position which sits right side on the column. We’ll use this div as column resizer handle.

The setListeners function adds mousedown event to provided div element, so, when someone press the mouse button on that div (to resize the column) the mousedown event will trigger, where we store the values of current mouse position, the target column width and the next column width. The mousemove event listener add the difference previous and current mouse position pageX to current and next columns to resize the column. On mouseup event we’ll clear all the stored values.

function setListeners(div)< var pageX,curCol,nxtCol,curColWidth,nxtColWidth; div.addEventListener('mousedown', function (e) < curCol = e.target.parentElement; nxtCol = curCol.nextElementSibling; pageX = e.pageX; curColWidth = curCol.offsetWidth if (nxtCol) nxtColWidth = nxtCol.offsetWidth >); document.addEventListener('mousemove', function (e) < if (curCol) < var diffX = e.pageX - pageX; if (nxtCol) nxtCol.style.width = (nxtColWidth - (diffX))+'px'; curCol.style.width = (curColWidth + diffX)+'px'; >>); document.addEventListener('mouseup', function (e) < curCol = undefined; nxtCol = undefined; pageX = undefined; nxtColWidth = undefined; curColWidth = undefined; >); >

We'll add a class to column selector div by editing the createDiv function.

Now style the columnSelector class:

//var tables = document.getElementsByClassName('flexiCol'); var tables = document.getElementsByTagName('table'); for (var i=0; i function resizableGrid(table) < var row = table.getElementsByTagName('tr')[0], cols = row ? row.children : undefined; if (!cols) return; table.style.overflow = 'hidden'; var tableHeight = table.offsetHeight; for (var i=0;ifunction setListeners(div)< var pageX,curCol,nxtCol,curColWidth,nxtColWidth; div.addEventListener('mousedown', function (e) < curCol = e.target.parentElement; nxtCol = curCol.nextElementSibling; pageX = e.pageX; var padding = paddingDiff(curCol); curColWidth = curCol.offsetWidth - padding; if (nxtCol) nxtColWidth = nxtCol.offsetWidth - padding; >); div.addEventListener('mouseover', function (e) < e.target.style.borderRight = '2px solid #0000ff'; >) div.addEventListener('mouseout', function (e) < e.target.style.borderRight = ''; >) document.addEventListener('mousemove', function (e) < if (curCol) < var diffX = e.pageX - pageX; if (nxtCol) nxtCol.style.width = (nxtColWidth - (diffX))+'px'; curCol.style.width = (curColWidth + diffX)+'px'; >>); document.addEventListener('mouseup', function (e) < curCol = undefined; nxtCol = undefined; pageX = undefined; nxtColWidth = undefined; curColWidth = undefined >); > function createDiv(height) < var div = document.createElement('div'); div.style.top = 0; div.style.right = 0; div.style.width = '5px'; div.style.position = 'absolute'; div.style.cursor = 'col-resize'; div.style.userSelect = 'none'; div.style.height = height + 'px'; return div; >function paddingDiff(col) < if (getStyleVal(col,'box-sizing') == 'border-box')< return 0; >var padLeft = getStyleVal(col,'padding-left'); var padRight = getStyleVal(col,'padding-right'); return (parseInt(padLeft) + parseInt(padRight)); > function getStyleVal(elm,css) < return (window.getComputedStyle(elm, null).getPropertyValue(css)) >>;

Answer by Mazikee Foley

Add the HTML table markup,Optionally add a store library,Add the resizable-table-columns.css file to the page., Simple Javascript resizable table columns

  
No. Name Counrty Region City Street Post Code Last updated UUID
1 Eugenia Serbia MN Minneapolis Ap #207-8285 Nibh Rd. 41754 2017-11-15T16:52:00-08:00 E212DAC2-220E-9589-D96A-3B58242E9817

Answer by Wesson Miles

1. Load the jQuery and resizableColumns javascript and CSS files into your HTML document., Home / Others / Make Table Columns Resizable with jQuery,A light weight and easy to use jQuery plugin to make any HTML table columns resizable. The resizableColumns is a jQuery and CSS based plugin that lets you make resize able columns of tables. ,3. Active the plugin by calling it with the selector ".resizable" in jQuery document ready function.

1. Load the jQuery and resizableColumns javascript and CSS files into your HTML document.

2. Create HTML table with the "resizable" class.

  
Subject Sem1 Sem2 Total
Total
Physics-1
Engoneering Physics
Engineering Mathematics

3. Active the plugin by calling it with the selector ".resizable" in jQuery document ready function.

Answer by Alan Palmer

The table-layout property defines the algorithm used to lay out table cells, rows, and columns.,If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:,Tip: The main benefit of table-layout: fixed; is that the table renders much faster. On large tables, users will not see any part of the table until the browser has rendered the whole table. So, if you use table-layout: fixed, users will see the top of the table while the browser loads and renders rest of the table. This gives the impression that the page loads a lot quicker!

Definition and Usage

The table-layout property defines the algorithm used to lay out table cells, rows, and columns.

Answer by Ben Dunn

This article will explore how to resize table columns with React and CSS Grid.,Now if you hover or click the right edge of any column in the table, you should see a border appear. This is our resize handler.,Please note that what we'll build is not quite a production ready solution. It's enough to illustrate how table columns can be resized, and provides a React-specific head start to a final solution.,This useEffect will run only on mount, but could easily be updated to run if new table rows or columns are added dynamically.

import < useState, useCallback, useEffect, useRef >from 'react'; const Table = (< headers, minCellWidth, tableContent, >) => < const [tableHeight, setTableHeight] = useState('auto'); const [activeIndex, setActiveIndex] = useState(null); const tableElement = useRef(null); return . >export default Table;

Источник

Resizable Table Columns With Drag and Slide Feature | Drag to Resize

resizable table columns

Previously I have shared a sorting datatable program, but this is a table with column resize feature. Basically, a table column resizes program you will see popular tables software like excel, google sheet, etc. Where we can adjust the column’s width by hold and dragging the sides. This is also important in websites UI design, where user can resize the columns and can see full contents easily.

Today you will learn to create a table with Drag to Resize column feature. Basically, there is a table with 8 columns and multiple rows. There are header items and thin separator lines in every column. You can resize the columns by just hold click and drag left or right. The table is fully flexible you can drag and slide for resizing, then a horizontal scroll bar will automatically appear.

So, Today I am sharing Resizable Table Columns With Drag and Slide Feature. There have used HTML to create the layout, CSS for styling, and JavaScript for functioning. This table is perfect for backend integration where admin can see user’s data or sales data, or anything else. You can use this program on your website for better users experience.

If you are thinking now how this resizable table program actually is, then the preview given below.

Preview Of Drag to Resize Columns

See this video preview to getting an idea of how this program looks like.

Now you can see this program visually, also you can see it live by pressing the button given above. If you like this program, then get the source code of its.

Resizable Table Columns With Drag and Slide Source Code

Before sharing source sharing, let’s talk about it. First I have created a table using HTML < table >tag, and created & sections inside it. Inside the < thead >tag I have put all the headings which are in the top nav section. There I have used HTML Data-* attribute to store and pass custom data. Inside every heading I have placed a span for drag and slide item.

Now using CSS I have placed all the elements in the right place, as you can see in the preview. There I have used grid display command display : grid ; to create the flexible layout, and used other grid CSS commands. There I have sticky position for table heading, it will fix and stick the table head on scroll down. I have used fr values in the grid commands.

JavaScript handling here the drag and resize column feature. There I have fetched the table using JS document . querySelector command and stored in conts. After that, I used Math . max command to resize and gave new width values to the column. And used many more commands like . addEventListener and if < >else < >statements etc.

Left all other things you will understand after getting the codes, I can’t explain all in writing. For creating this program you have to create 3 files. First file for HTML, second for CSS, and the third file for JavaScript. Follow the steps to creating this program without any error.

Create an HTML file named ‘index.html‘ and put these codes given below.

Источник

Читайте также:  Blocking code in javascript
Оцените статью