Jonas TM
Jonas TM

Reputation: 160

HTML table with resizable columns using percentage width

There are plenty solutions for resizable tables out there. But all of them have in common that they are using pixel widths and not percentage widths.

In my use case my tables col widths need to be with a percentage width or at least set to an percentage width after the resize action. My implemented solution is buggy when starting to resize.

http://jsfiddle.net/bg843pkt/24/

var thElm;
var startOffset;

var eG;

Array.prototype.forEach.call(
  document.querySelectorAll("table th"),
  function (th) {
    th.style.position = 'relative';

    var grip = document.createElement('div');
    grip.innerHTML = " ";
    grip.style.top = 0;
    grip.style.right = 0;
    grip.style.bottom = 0;
    grip.style.width = '5px';
    grip.style.position = 'absolute';
    grip.style.cursor = 'col-resize';
    grip.addEventListener('mousedown', function (e) {
        thElm = th;
        startOffset = th.offsetWidth - e.pageX;
    });

    th.appendChild(grip);
  });

document.addEventListener('mousemove', function (e) {
  if (thElm) {
    thElm.style.width = startOffset + e.pageX + '%';
    eG = e.pageX;
  }
});

document.addEventListener('mouseup', function () {
    thElm = undefined;
});

How it acts

How it should act

Can anyone tell me how i can implement this functionality with percentage width without any buggy behaviour?

Upvotes: 0

Views: 3889

Answers (2)

Alan
Alan

Reputation: 1

I created table with column resize, the initial width is percentage. When you resize the column, you can get the PX of the column first and then convert it to percentage according to the width of the whole table. https://biechao.github.io/2019/11/20/storybook-static/?path=/story/table--resizable-column-table

Upvotes: 0

Jonas TM
Jonas TM

Reputation: 160

I created a working example but it is using an older jQuery Version.

http://jsfiddle.net/Ln280eqc/17/

    $("table").resizableColumns();

Source: https://github.com/dobtco/jquery-resizable-columns

Upvotes: 2

Related Questions