Implementing automatic vertical scrolling for dynamically added rows in a table's body

Check out this fiddle I created:

https://jsfiddle.net/desytec/m69q2xwr/34/

<style>
.table-scroll tbody {
    position: absolute;
    overflow-y: auto;
    height: 250px;
}
</style>

<script>
var count = 0;

$(document).ready(function () {
    $('#btnAdd').on('click', function() {
      var tableBody = $('#mytable tbody');
      var newRow =
         '<tr id="tr_' + count + '">' +
             '<td>Test Row ' + count + ' Col 1</td> ' +
             '<td>Test Row ' + count + ' Col 2</td>'
         '</tr>';
         tableBody.append(newRow);
         count++;
         if (count == 3)
             tableBody.addClass('table-scroll');
    });
    $('#btnDelete').on('click', function() {
      var tableBody = $('#mytable tbody');
         tableBody.children().last().remove();
         count--;
         if (count == 2)
             tableBody.removeClass('table-scroll');
    });
});
</script>

<div class="row">
    <div class="row ml-4">
        <button id="btnAdd" type="button" class="btn btn-secondary btn-circle m-4">Add row</button>    
    </div>
    <div class="col-6">
        <button id="btnDelete" type="button" class="btn btn-secondary btn-circle m-4">Delete row</button>    
    </div>    
</div>

<table id="mytable" class="table table-striped dt-responsive w-100 table-bordered display nowrap table-hover mb-0">
    <thead>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

I'm trying to implement a vertical scroll bar in the table body while keeping the header fixed when dynamically adding rows.

Despite my attempts, adding a class to the table body when reaching 3 rows does not seem to work for displaying the scrollbar. Any suggestions on the correct approach?

Thanks, Jaime

Answer №1

It appears that a small tweak to the styling will help you achieve your desired outcome. I have repositioned 'table-scroll' to be a class of the 'table' element because I needed to make adjustments to the header row when the scrollbar is visible. In the CSS, I have relocated the overflow-y property to .table-scroll tbody and to prevent the TDs from resizing unintentionally, I have included a rule to maintain them at 50vw. When the scrollbar shows up, there is a slight misalignment between the header and body. To address this, I have added a shim on the header row to compensate for it - while it may not be perfect, it is very close!

Rather than relying on the count to determine the scroll breakpoint, I have instead measured the height of the tbody.

.table-scroll {
  position: absolute;
  overflow-y: auto;
  height: 150px;
  display:block;
}

.table-scroll td {
  width: 100vw;
}

$(document).ready(function() {
  $('#btnAdd').on('click', function() {
    var tableBody = $('#mytable tbody');
    let count = tableBody.children().length
    var newRow =
      '<tr id="tr_' + count + '">' +
      '<td>Test Row ' + count + ' Col 1</td> ' +
      '<td>Test Row ' + count + ' Col 2</td>'
    '</tr>';
    tableBody.append(newRow);
    adjustTable()
  });
  $('#btnDelete').on('click', function() {
    var tableBody = $('#mytable tbody');
    tableBody.children().last().remove();
    adjustTable()
  });
});

function adjustTable() {
  let maxHeight = 250
  // console.log($('#mytable tbody').height() > maxHeight)
  if ($('#mytable tbody').height() >= maxHeight) $('#mytable').addClass('table-scroll');
  else $('#mytable').removeClass('table-scroll');

}
.table-scroll  {
  height: 285px;
}

.table-scroll tbody {
  position: absolute;
  overflow-y: auto;
  height: 250px;
}

.table-scroll tbody td {
  width: 50vw;
}

#mytable .shim {
  display: none;
  width: 13px;
  padding: 0;
  background: #DFDFDF;
}

#mytable.table-scroll .shim {
  display: table-cell;
}

.table-container{
margin-bottom:15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="76141919020502041706364358465847">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1b7974746f686f697a6b5b2e352b352a">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
<div class="row">
  <div class="row ml-4">
    <button id="btnAdd" type="button" class="btn btn-secondary btn-circle m-4">Add row</button>
  </div>
  <div class="col-6">
    <button id="btnDelete" type="button" class="btn btn-secondary btn-circle m-4">Delete row</button>
  </div>
</div>
<div class='table-container'>
<table id="mytable" class="table table-striped dt-responsive w-100 table-bordered display nowrap table-hover mb-0">
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th class='shim'></th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>
</div>
<p>Other content...</p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Move a div in front of a fade-toggle

I am currently working on a website primarily using PHP, but I have very little knowledge when it comes to JavaScript/jQuery. I managed to create a feature where I press a button and a div fades in, but it abruptly moves the divs under it. Is there a way f ...

What is the significance of the source element in Vue3's audio element?

Playing mp3 files works in Vue 2, but not in Vue3. <template> <audio src="../file_example_MP3_700KB.mp3" controls ></audio> </template> In Vue3, the code needs to be modified as follows: <template> <audi ...

Tips for Eliminating Unnecessary Space Above the Navigation Bar

I have a problem with the top navbar on my test site. There is some extra space above it that I want to remove so that the navigation extends all the way up to cover the viewport. Here is an image of what I'm trying to achieve: https://i.stack.imgur.c ...

Counting JSON Models in SAP UI5

I am encountering a particular issue. Please forgive my imperfect English. My goal is to read a JSON file and count the number of persons listed within it. I want this result to be stored in a variable that is linked to the TileContainer. This way, whenev ...

Display Modal upon EJS Page Loading

Is it possible to display a modal when my EJS page loads? If so, how can I achieve this? My project is built with Node.js and Express.js. Thank you in advance. ...

Unable to display an image prior to its upload

I'm facing an issue with changing the image for my second data. It's not updating, but when I try it with the first data, it works fine. I'm unsure why this is happening and would appreciate any help in resolving it. Here is the form where ...

Updating View in Angular 2 ngClass Issue

I'm encountering some challenges with updating my view using ngClass despite the back end updating correctly. Below is my controller: @Component({ selector: 'show-hide-table', template: ' <table> <thead> ...

Trouble incorporating JSON in JQuery and MVC

I am attempting to trigger my controller using JavaScript and jQuery. Below is the jQuery code I have: <script type="text/javascript> $('form').submit(function (e) { e.preventDefault(); $.ajax({ type: "POST", url: $(this).attr(" ...

Twitter typeahead not functioning properly when used in conjunction with ajax requests

I have limited experience in the frontend world and I'm currently working on getting this to function properly. $('#the-basics .typeahead').typeahead({ hint: true, highlight: true, minLength: 6 }, { source: function (query, ...

Is there a way to adjust the height overflow using a percentage?

I have a coding dilemma here where I am attempting to make the SearchLocationCards overflow. It seems to work fine with 'px' and 'vh' values, but the '%' value doesn't seem to have any effect. How can I adjust the height ...

Utilizing Wordpress post images to dynamically change background URLs in CSS

Is there a way to dynamically set a background image in CSS using PHP, specifically the Wordpress post image? background: <?php if(has_post_thumbnail()){ $img = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'dest ...

Tips for handling numerous buttons in ionic?

I'm currently working on an app that includes surveys. In this app, users are required to answer by selecting either the Yes or No button. The desired behavior is for the chosen button to turn blue once clicked, while the other button should maintain ...

Fluid Centered UL with Bullet Points

We have received a unique request from one of our clients. They are asking for the content within a specific <ul> to be centered along with the icons. Centering and adding icons are doable, but the challenge lies in centering the <li> elements ...

Spin and Return: CSS Animation with Rotation

I am attempting to create an animation with this arrow that will move up and down, as well as rotate or change its direction at 0% and 100%. However, my current issue is that the arrow rotates for a second at 100% and then reverts back to its previous dire ...

Display a 'Please hold on' notification on the JSP page after the user clicks a button. Once the processing is finished on the servlet, the notification should disappear

When the download button is clicked on my JSP page, the onDownload function calls a servlet with the following function. I want to display an alert saying 'Please Wait' during processing and then close the alert once the processing is complete in ...

Updating the total quantity using ajax in Laravel 8

I've set up my shopping cart to use AJAX for adding items, which is working fine. However, I'm unsure how to update the total quantity number displayed in the header. There are no input fields for selecting quantity, so I want the quantity to inc ...

Customizing hyperlink styles with JavaScript on click

Hey there! I'm experimenting with something new. I've managed to change the background color of each link after it's clicked, but now I'm facing a challenge: How can I revert the original style when another link is clicked? Here's ...

Display the onclick event of multiple buttons on a web page

I am currently working on extracting the "onclick" attribute (onclick="openDirection( 41.051777,28.986551)") from the first button element within each li element. My goal is to display all of the coordinates. In the provided code snippet, I have been abl ...

What is the best way to retrieve the first item in owl carousel's content?

I need help creating a slider with two sections: top and bottom. My goal is to display the content from the bottom slider on the top slider. I tried adding a class to the first item element, but it didn't work. If anyone knows how to target the first ...

The modal window does not display a scroll bar

I'm currently facing an issue where the scroll bar is not appearing on my page when more elements are added. In addition, I have a modal that covers the entire page when clicking on an item. However, changing the CSS position: fixed property affects ...