Guide on freezing a Header and Columns in an HTML table with the help of Jquery

I am attempting to adjust the header and columns, as well as change their background color in a Table using JQuery. I have generated the table in JQuery from some JSON data.

I have experimented with the 'translate()' function to lock them into place.

var translate = "translate(5px,0)";

"This method helps me fix the column or header, however, the main issue arises when I scroll horizontally first and then vertically; the first <th/> of the header scrolls while the rest stay fixed (refer to the output image mentioned in the question)."

Allow me to share the code:

HTML:

This is my HTML where I call 'MyJS' from <script/>.

 <div class="row" >
    <div class="tblMain" id="tblMainDiv">

    </div>
</div>

<script>
  $("#tblMainDiv").MyJS({
                    Data: data.Data,
                    ColoredColumns:["Sarika"]
  });                                                            
<script/>

JS:

'_params' stand for the parameters and '_params.Data' represents the Json data of the table. '_myTableTr' refers to the tr of the table.

   var _collection = JSON.parse(_params.Data);
   var _myTableColumns = [];

   var _collection = JSON.parse(_params.Data); // Parsing the Json Data.
        for (var i in _collection[0]) {
            _myTableColumns.push(i); // grabbing column headers and pushing them into the collection.
        }

        // Adding table heads
        if (_myTableColumns.length > 0) {  
            for (var i = 0; i < _myTableColumns.length; i++) {
                var _myTableTh= document.createElement("th");
                _myTableTh.innerHTML = _myTableColumns[i];
                _headerTr.appendChild(_myTableTh);
            }
        }

        // adding table data
        for (var i = 0; i < _collection.length; i++) {
            _myTableTr = _myDatatable.insertRow(-1);
            for (var j = 0; j < _myTableColumns.length; j++) {
                var cell = _myTableTr.insertCell(-1);
                cell.innerHTML = _collection[i][_myTableColumns[j]];
            }
        }

And here's the code for Freezing:

Here, I am attempting to fix only the first column, but eventually, I may want to fix multiple random columns.

//For Header and Specific columns to be fixed .
    var lastPosY = 0;
    var lastPosX = 0;

    $("#"+$(this).attr('id')).scroll(function () {
        var currPosX = this.scrollLeft; // get current position of Column.
        var currPosY = this.scrollTop;

        if (lastPosY != currPosY && (lastPosY > 0 || currPosY > 0)) {

            $('#tblMyDataTable' + $(this).attr('id') + ' thead th:first-child').removeAttr('style');
            var translate = "translate(0," + (this.scrollTop) + "px)"; // getting translate pixels based on the current position of the bar
          $($('#tblMyDataTable' + $(this).attr('id')).find("thead").eq(0)).css('transform', translate);

        }
        else {

          translate = "translate(" + (this.scrollLeft) + "px,0)"; 
           if (lastPosX != currPosX) {
               $('#tblMyDataTable' + $(this).attr('id') + ' thead th:first-child').css('transform', translate);
               $('#tblMyDataTable' + $(this).attr('id')+ 'tbodytrtd:first-child').css('transform', translate); 
            }
        }

        lastPosX = currPosX;
        lastPosY = currPosY;

    });

CSS:

.myDataTable {
width: 100%;
overflow-x: scroll;
border-collapse: separate !important;
border: 1px solid #000;}

.tblMain {
margin:20px;}

.myDataTable > tbody > tr:nth-child(even)>td {
background-color: #e6e6e6;}

.myDataTable > tbody > tr:nth-child(odd) > td {
background-color: #fff;}

.tblMain {
height: 50vh;
overflow-y: auto;}

The Output I Am Getting: https://i.sstatic.net/Ax4Fk.jpg

Please assist me in resolving this issue and changing the background color of the fixed elements. Thank you.

Answer №1

If you want to achieve this, you can utilize a pair of tables. One table will be designated for the table header, while the other will hold the table data. Then, implement a resize event to adjust the column widths accordingly.

<table id="header">
   <thead><tr>
     <th>Col1</th>
     <th>Col2</th>      
   </tr></thead>
</table>
<table id="body">
   <tbody><tr>
     <td>Data1</td>
     <td>Data2</td>      
   </tr></tbody>
</table>

The jQuery datatables plugin offers this feature.

<style>

   thead tr {
       background-color: red; /* Your color */
   }

</style>

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

Tips for efficiently parsing a massive JSON file?

Looking for a solution to efficiently read a large JSON file: { "Count": 361888, "Items": [ { "S3Url": {"S": Grouper/1904/1/private/drafts/D1_2/siepon_D1_2/siepon_C11_D1‌​_2_diff.pdf" }, "JSONFile": {"S": Grouper/1904 ...

Concealing a column within an Angular Material table

I'm currently faced with a challenge involving an Angular Material table containing numerous columns. My goal is to selectively hide certain columns based on specific CSS media queries. This is the code snippet I have experimented with so far: HTML: ...

Validation does not function properly when using a blade template

I'm experiencing an issue with validating my form. When I attempt to submit the form, it always refreshes the page without performing any validation. The initial process begins at accountDashboard.blade.php @section ('content') <div cl ...

The sticky navigation bar isn't functioning properly, even though the code worked perfectly on W3School

I recently encountered an issue while trying to create a sticky navbar that would remain fixed after scrolling past a certain point. I found and customized some code from w3schools that included an animation effect, and it worked perfectly in their demo. H ...

Creating customized JQuery UI tabs to perfectly accommodate the available horizontal space

Can JQuery UI Tabs be modified to fill the horizontal space and stack to the left? In order to achieve this, could we consider using a markup like the one below: <table width="100%"> <tr> <td> ...content... </td> ...

.Certain IDs on a website may not respond to clicks due to various reasons

I have created a JavaScript file to automatically click a button on a website using a Chrome extension. When testing the code using Chrome Script snippet, I noticed that it worked for some IDs but not for others. Can someone please help me with this issue? ...

Where is the best position to place the navbar in responsive design and grid layouts?

I am creating a small blog website using metalsmith and the PureCSS framework. The layout consists of a simple three-row structure like this: <div class="pure-g"> <div class="pure-u-1"> Navbar </div> <div class="pure-u-1"> ...

Ways to exhibit API information leveraging the prowess of Ajax

I am looking for a way to utilize the API in order to present data in an organized manner, similar to the following example: Job Title: Agricultural and Related Trades Percentage of Occupancies in Area: 15.41% Unfortunately, my attempt to showcase the d ...

jqGrid - What is the best way to set up jsonreader in conjunction with Jayrock?

Seeking insights from anyone familiar with this topic. The JSON string that works well with jqGrid looks like this: {'page':'1','total':1,'records':'4','rows':[{'id':1,'title' ...

Retrieve the id of the clicked hyperlink and then send it to JQuery

<a class = "link" href="#" id = "one"> <div class="hidden_content" id = "secret_one" style = "display: none;"> <p>This information is confidential</p> </div> <a class = "link" href="#" id = "two" style = "display: non ...

What is the best way to transform Adobe XD designs into HTML and CSS with Vue.js?

I am looking to create a single page application with vue.js and came across this helpful reference at . A colleague has created a prototype using Adobe XD, and now my task is to transform it into HTML/CSS while making it functional and connecting it to an ...

JSON format for date and time conversion

Dear Jason, [Serializable] public class MyModel { public int Id {get;set;} public DateTime date {get;set;} } [HttpPost] public ActionResult SchedulesDropdownIndexChanged(MyModel schedule) { objScheduleModel = new ScheduleModel( ...

Flaw in Basic Function Logic Using HTML, JavaScript, and CSS

Need some help with the function onBall3Click1 (code is at the bottom). The ball should act like a lightbulb: ON - turn YELLOW, OFF - turn GRAY. I've been trying to figure out the logic behind it for so long and can't seem to find the issue... ...

The resizing issue of Textarea during transitions

Whenever I add the transition property to a textarea, it automatically affects the resizing function of the textarea. Is it possible to disable the transition only when resizing the textarea, but not for the textarea itself? <textarea name="" id="" cla ...

Store the ID of a div in a variable

Currently, I have transformed rock paper scissors from a terminal/console game using prompts and alerts to something playable in a web browser through the use of the jQuery library. In order to achieve this transition, I created images for each hand - roc ...

Is it possible to automatically scroll the contents inside a div tag?

I have a large amount of data within a div. To manage this, I've utilized the overflow property to hide the excess content. Now, my goal is to automatically scroll the scrollbar to the left in order to display the 4th, 5th, and 6th elements of the fir ...

Slanted background div that adjusts to the screen size

I'm struggling to create a slanted angle div that remains responsive as the screen size changes. Unfortunately, my current layout breaks completely when the screen gets bigger. If you'd like to take a look at what I've been working on so fa ...

Personalize API responses in Spring Boot depending on the roles of the user

Implementing authorization logic for controller's methods in a way that restricts access based on user role is essential. Consider an endpoint called Interview with the method findInterviewById(id), which returns an Interview object. Users in the app ...

Ignored CSS hover effect on touch screen devices

I've added a new div with an HTML button: $('.nav').append('<button class="restart">Restart</button>'); This button has some CSS properties for hover effects. However, I am facing an issue where on touch-screen device ...

Is it possible to create a struct that automatically transforms from serde_json::Value using Deserialize?

When it comes to deserializing from a string directly into a struct, everything works flawlessly. However, there are instances where you might already have a serde_json::Value and wish to convert it into a struct. For example, imagine you need to load a R ...