Search code examples
javascripthtmlcsshtml-table

How can I add a scrollbar that just scrolls one column in an html table?


I'm trying to add a scrollbar to a full column in an html table. In this example https://jsfiddle.net/6wpdc4tL/ :

enter image description here

there would be two scrollbars, one under the light blue SCROLL column and another under the light green SCROLL2 column. Each would only scroll their column and they would scroll the whole column at once. Both the Row and Sec Row columns would stay the same width and not scroll.

<table>
    <tr>
      <th class="headcol">1</th>
      <td class="long1">SCROLL SCROLL SCROLL SCROLL</td>
      <th class="middlecol">1</th>
      <td class="long2">SCROLL2 SCROLL2 SCROLL2 SCROLL2</td>
    </tr>
    <tr>
      <th class="headcol">2</th>
      <td class="long1">SCROLL SCROLL SCROLL SCROLL</td>
      <th class="middlecol">2</th>
      <td class="long2">SCROLL2 SCROLL2 SCROLL2 SCROLL2</td>
    </tr>
  </table>

How can I add scrollbar that just scrolls one column in an html table?


Solution

  • Ok, here's what you'll need to do. I had to write some JavaScript to manipulate the table to a format where I could set the width of the column, so only the scrollbar appeared once at the bottom.

     const klasses = ['headcol', 'long1', 'middlecol', 'long2']
      
     const newTable = document.createElement("table");
     newTable.setAttribute("id", "newTable");
     const tr = document.createElement('tr');
     
     klasses.forEach((k, idx) => {
       const cell = document.createElement(idx % 2 === 0 ? 'th' : 'td');
       cell.setAttribute('class', `${k}new`)
       const div = document.createElement('div');
       const cTable = document.createElement('table');
    
       const nodes = document.querySelectorAll(`.${k}`);
       nodes.forEach(n => {
          const cTr = document.createElement("tr");
          cTr.appendChild(n);
          cTable.appendChild(cTr);
       });
    
       div.appendChild(cTable)
       cell.appendChild(div)
       tr.appendChild(cell);
     });
     
     newTable.appendChild(tr);
     document.body.appendChild(newTable);
     
    .headcolnew, .middlecolnew {
      vertical-align: top;
    }
    
    .long1new, .long2new {
      max-width: 125px;
      overflow-x: scroll;
      white-space: nowrap;
    }
    <table>
        <tr>
          <th class="headcol">1</th>
          <td class="long1">SCROLL SCROLL SCROLL SCROLL</td>
          <th class="middlecol">1</th>
          <td class="long2">SCROLL2 SCROLL2 SCROLL2 SCROLL2</td>
        </tr>
        <tr>
          <th class="headcol">2</th>
          <td class="long1">SCROLL SCROLL SCROLL SCROLL</td>
          <th class="middlecol">2</th>
          <td class="long2">SCROLL2 SCROLL2 SCROLL2 SCROLL2</td>
        </tr>
      </table>