How to make <div> scrollable from bottom

Viewed 58

I made a table inside a div to make it scrollable;

<div style="overflow-y: scroll; height:100px; width:100px;">
  <table
    <thead>
      <tr>
        <th>a</th>
        <th>b</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>a</td>
        <td>a</td>
      </tr>
      <tr>
        <td>b</td>
        <td>b</td>
      </tr>
      <tr>
        <td>t</td>
        <td>t</td>
      </tr>
      <tr>
        <td>a</td>
        <td>a</td>
      </tr>
      <tr>
        <td>b</td>
        <td>b</td>
      </tr>
      <tr>
        <td>t</td>
        <td>t</td>
      </tr>
    </tbody>
  </table>
</div>

This table is scrollable from top to bottom. How can I make the table's overflow start at the bottom and make it scroll upwards?

2 Answers

You need to use javascript for this. Using scrollTop for accessing the scroll offset from the top (default is 0). So you have to get the div's height and set the scrollTop of the div to its height. To get the height, I used getBoundingClientRect().height

let tableDiv = document.getElementById('main');
tableDiv.scrollTop = tableDiv.getBoundingClientRect().height;
<div id="main" style="overflow-y: scroll; height:100px; width:100px;">
<table
<thead>
<tr>
<th>a</th>
<th>b</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>a</td>
</tr>
<tr>
<td>b</td>
<td>b</td>
</tr>
<tr>
<td>t</td>
<td>t</td>
</tr>
<tr>
<td>a</td>
<td>a</td>
</tr>
<tr>
<td>b</td>
<td>b</td>
</tr>
<tr>
<td>t</td>
<td>t</td>
</tr>
</tbody>
</table>
</div>

Your HTML content:

<div class="scorllable-table" id="scrollTable">
  <table>
    <thead>
      <tr>
        <th>a</th>
        <th>b</th>
      </tr>
    </thead>
    
    <tbody>
      <tr>
        <td>a</td>
        <td>a</td>
      </tr>
      <tr>
        <td>b</td>
        <td>b</td>
      </tr>
      <tr>
        <td>t</td>
        <td>t</td>
      </tr>
      <tr>
        <td>a</td>
        <td>a</td>
      </tr>
      <tr>
        <td>b</td>
        <td>b</td>
      </tr>
      <tr>
        <td>t</td>
        <td>t</td>
      </tr>
    </tbody>
  </table>
</div>

Your CSS content:

.scorllable-table {
  overflow-y: scroll;
  height: 100px;
  width: 100px;
}

If you want to do this using JavaScript only, then please try with this.

var scrollableDiv = document.getElementById("scrollTable");
scrollableDiv.scrollTop = scrollableDiv.scrollHeight;

If you want to do this using jQuery, then use the below code.

$("#scrollTable").scrollTop($("#scrollTable")[0].scrollHeight);

If you want to smooth scroll, then try with this.

$('#scrollTable').stop().animate({
  scrollTop: $('#scrollTable')[0].scrollHeight
}, 500);

Enjoy, Thanks. :)

Related