Skip to content
Advertisement

Double Horizontal Scroll on Table – JQuery

I am trying to add double horizontal scrolls – one above the table and one below it. The table “MUST be based on percentage” and not a fixed width. How do I accomplish this with JQuery?

I need the table to span 100 percent width and have 2 scrollbars that are synced. With alot of content, the bottom scrollbar gets lost from the user…

JSFIDDLE – https://jsfiddle.net/rbla/8usk97ch/6/

HTML

 <div style="overflow-x:auto;">

 <table id="select" class="info">
   <thead>
     <tr class="row">
       <th>1</th>
       <th>2</th>
       <th>3</th>
       <th>4</th>
       <th>5</th>

       <th>6</th>
       <th>7</th>
       <th>8</th>
       <th>9</th>
       <th>10</th>

       <th>11</th>
       <th>12</th>
       <th>13</th>
       <th>14</th>
       <th>15</th>

       <th>16</th>
       <th>17</th>
       <th>18</th>
       <th>19</th>
       <th>20</th>
     </tr>
   </thead>

   <tbody>
       <td>content 1</td>
       <td>content 2</td>
       <td>content 3</td>
       <td>content 4</td>
       <td>content 5</td>

       <td>content 6</td>
       <td>content 7</td>
       <td>content 8</td>
       <td>content 9</td>
       <td>content 10</td>

       <td>content 11</td>
       <td>content 12</td>
       <td>content 12</td>
       <td>content 14</td>
       <td>content 15</td>

       <td>content 16</td>
       <td>content 17</td>
       <td>content 18</td>
       <td>content 19</td>
       <td>content 20</td>
    </tbody>
   </table>

   </div>

CSS

  table.info {
     width: 98%;
     margin: 0 1%;
     border-collapse: collapse;
   }

 .row {
     background:#CCC;
  }

 td {
     white-space: nowrap;
 }

Advertisement

Answer

Add one more div with horizontal scroll:

<div id="scroll1" style="overflow-x:auto;">
    <div style="height: 1px;margin: 0 1%;"></div>
</div>

Then synchronize both scroll events via jQuery.

$("document").ready(function(){
    $("#scroll1 div").width($("#select").width());
    $("#scroll1").on("scroll", function(){
        $("#scroll2").scrollLeft($(this).scrollLeft());
    });
    $("#scroll2").on("scroll", function(){
        $("#scroll1").scrollLeft($(this).scrollLeft());
    });
});

Here is my jsFiddle example

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement