Is it possible to immobilize dynamic table columns seamlessly without resorting to an unsightly loop or being confined to

I have a table and I'd like to freeze the header row along with a specific number of columns. While I managed to achieve this, it's quite slow on larger tables. Is there a more efficient approach to get the same outcome? I experimented with using $(this).position().left+'px' instead of freezePos, but it only worsened the performance (is there a tool available for comparing speeds?).

The process of calculating positions seems cumbersome. Ideally, I would prefer to lock cells along the x axis without explicitly setting a left property. Additionally, fixing widths on these cells isn't optimal. Are there any other methods I can implement to optimize this?

Is there no CSS equivalent to position: fixed-x?

$.fn.freezeColumns = function() {
  var freezePos = 0;
  $('thead th').each(function(index, val) {
    if(index == 2) return false; // Exit after n elements
    var $self = $(this);
    var curWidth = $self.outerWidth();
    $('th:nth-child(' + parseInt(index+1) + '), td:nth-child(' + parseInt(index+1) + ')').addClass('sticky').css('left', freezePos);
    freezePos += curWidth;
  });
};
$(document).freezeColumns();
body {
  font-family: 'Lucida Grande';
}

div {
  width: 500px;
  height: 200px;
  overflow: scroll;
}

td,
th {
  padding: 2px 10px;
  white-space: nowrap;
}

thead th {
  position: sticky;
  position: -webkit-sticky;
  top: 0;
  background: #146775;
  color: white;
  z-index: 3;
}

.sticky {
  position: sticky;
  position: -webkit-sticky;
}
th.sticky {
  z-index: 4;
}
td.sticky {
  background: #569CA8;
  color: white;
  z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <table cellspacing="0">
    <thead>
      <tr>
        <th>Header 1 Title</th>
        <th>Header 2 Title X</th>
        <th>Header 3 Title XX</th>
        <th>Header 4 Title XXX</th>
        <th>Header 5 Title XXXX</th>
        <th>Header 7 Title XXXXX</th>
        <th>Header 8 Title XXXXXX</th>
        <th>Header 9 Title XXXXXXX</th>
        <th>Header 10 Title XXXXXXX</th>
      </tr>
    </thead>
    <tbody>
      (Content rows truncated for brevity)
    </tbody>
  </table>
</div>

Answer №1

Instead of freezing the elements, I recommend creating a function that clones multiple rows along with the header and positions them absolutely over the originals. You could also apply an invisibility filter to the original rows if necessary.

Upon further review of the code, optimizing performance can be achieved by moving common attributes outside of the jQuery loop. Here's an example:

$.fn.newFreeze = function(num) {
  var left = 0;
  for (var i = 1; i < num + 1; i++) {
    left += i === 1 ? 0 : $(`th:nth-child(${i - 1})`).outerWidth();
    $(`th:nth-child(${i}),td:nth-child(${i})`).each(function() {
      $(this).css({
        left,
        zIndex: 4,
      })
    })
  }
}
th, td {
  position: sticky;
  position: -webkit-sticky;
}

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

Restrict the Angular ng-repeat directive to specific rows only

Suppose we have a JSON dataset listing all languages of books: $scope.data = [{ "title": "Alice in wonderland", "author": "Lewis Carroll", "lang": ["en"] }, { "title": "Journey to the West", "author": "Wu Cheng'en", "lang": [" ...

Integrating and deleting class elements

My jQuery Credit Card Plugin has a feature where it switches out a class to show an image of the credit card that was entered. However, I am facing an issue with clearing the credit card information each time a new one is entered. Is there a way to clear ...

Ajax request mistakenly interprets empty data as containing [ ] symbols

I am experiencing an issue with my code that retrieves all posts. Even when there are no posts available, the data being sent is still [], which means that no errors are occurring even when the data is empty. As an example, the result is always ["Hello"], ...

Implement consistent styling across several elements within a component

const GreenRow = styled.div` background-color: green; ` const RedRow = styled.div` background-color: red; ` const YellowRow = styled.div` background-color: yellow; ` const GreyRow = styled.div` background-color: grey; ` const MyComponent = () => ...

Having trouble with the submit form not functioning properly in the Firefox browser exclusively

Encountering an issue when submitting a form from a Bootstrap modal, specifically in Firefox. The code seems simple enough: $('#confirmBtn').click(function(e){ e.preventDefault(); $('#s-form').submit(); }); This function is ...

Inconsistent functionality: Twitter Bootstrap tabs malfunction when placed inside a modal

Within a rails application, I have successfully implemented loading the content of a modal window (bootstrap modal) using Ajax. The challenge arises when trying to integrate tabs (bootstrap tabs) within this loaded content. While the tabs are displayed co ...

Save the contents of the text area automatically at regular intervals

I am in need of assistance with implementing an "auto-saving" feature for a textarea. Essentially, I want to save a draft in our database whenever a user is typing in the textarea. For example, imagine a scenario where a user is writing a blog post. Every ...

Difficulty viewing image in Firefox using HTML <img> tag

I'm encountering an issue with rendering an img tag in an HTML page. The img source is a file located on a remote server. Surprisingly, when attempting to display the image in Firefox using: file://///server/folder1/folder2/name.jpg it shows up prop ...

Ensure that the if statement is appropriate for matching the Textarea and Div elements

When I click on an element within the removeFood division, I expect it to correspond with the item in the text area named newFoodName1. $(".removeFood").click(function() { var removedFood = ($(this).children('.dailyItem').text()) $(this).t ...

(RESPOND) Configuring a preset option for a Dropdown selection field

I am currently developing a frontend to demonstrate the behavior of a CRUD RESTful API. One specific requirement is that when the user selects the option "GET", the default value in the dropdown field labeled "Order-by" should be set to "Name". However, fo ...

Simplifying complex callback structures

In this scenario, I have created a callback function to handle object data processing. function (err, data) { var finalResult; if (data && data.result instanceof Array) { finalResult = data.result.map(function (value) { if ...

Determine if an HTML element contains a specific class using JavaScript

Is there a simple method to determine if an HTML element possesses a particular class? For instance: var item = document.getElementById('something'); if (item.classList.contains('car')) Remember, an element can have more than one clas ...

How to mimic a mouse hover effect with JavaScript

I'm attempting to replicate a mouse hover effect using JavaScript. Here is the code I have: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <style> #chart:hover { ...

Struggling with updating state using splice method within an onClick event in React Hooks

CODE DEMO I'm facing an issue with my code snippet where it appears fine when I console.log it, but fails to set the state. The goal is to delete a box by using splice when clicked, however, something seems to be preventing it from working properly. ...

Changing the value of a Redux object causes the TextInput within a FlatList item to lose focus

I have a nested object in my redux store that I am using to render my FlatList. Each item in the set contains a textInput to modify the reps in the set, but every time I change the value of the input, it becomes unfocused and the keyboard dismisses. Is the ...

Adding a new row within a table using jQuery at the center position

I am trying to add a new row at the beginning of a table right after the header row. The prepend() method is not working as expected because it inserts the new row before the header. Additionally, the after and before methods are also not giving me the des ...

Displaying a notification in React when the array of objects is empty

I need to create a notification based on whether my object contains any data or not. Initially, I store the data in a state called "data" and set it to null. When I receive data from the server, I update the data state with the returned data. If the data ...

What is the method for producing a vertical line of numerical dots utilizing CSS?

I am looking to add thick dots at specific locations along the vertical line between [div class="col-md-4"] and [div class="col-md-8"]. Here is what I have attempted: <div class="col-md-4" style="border-right:1px solid #333;"> <h1>1987</h1 ...

Fetching data dynamically in PHP

I am working on a search form with four filter textboxes. My goal is to submit and search only the textboxes that have values when the user submits the form. I understand how to achieve this using an if-else statement, but it seems too lengthy in terms o ...

Error encountered when utilizing sceneLoader to import a scene produced by the THREE.js Editor

An issue arises with the error message Uncaught TypeError: Cannot read property 'opacity' of undefined identified on three.js:12917 The current scene file in use is as follows: { "metadata": { "version": 4.3, "type": "Object", "gene ...