Click here to Skip to main content
15,905,914 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In a dynamically created table, I want to freeze the top row so that it always displays when the table is scrolled. The related piece of code is below. How can the header row get frozen? Thanks.

JavaScript
        function createTable(_records, cellWidth) {
            var _table = document.createElement("TABLE");

            var row = _table.insertRow(-1);
//            row.style.position = 'fixed';
            for (var i = 0; i < _records[0].length; i++) {
                var headerCell = document.createElement("TH");
                headerCell.innerHTML = _records[0][i];
                headerCell.bgColor = '#FFCCFF';     // pale pink
                headerCell.style = 'first-row-style';
                headerCell.style.height = '24px';
                //headerCell.style.position = 'fixed';
                headerCell.style.textAlign = 'center';
                headerCell.style.borderLeft = '.5px solid black';
                row.appendChild(headerCell);
            }
        ....
        }


What I have tried:

How to freeze header row of a scrollable table?
Posted
Updated 6-Jul-16 4:21am

1 solution

The freezing of the headers is done by setting the position property of the element to absolute. This would allow your element to float anywhere, you want it to. Absolute positioning is really very helpful in such scenarios, where you want an element to float on another element such as in the cases of scrolling while keeping the headers (or the column names) in their own position.

position - CSS | MDN[^]
Tryit Editor v3.0[^]

In your case, it would be,
JavaScript
headerCell.style.position = "absolute";

// Rest of the configurations to keep the header on top
headerCell.style.top = "0px";

But sometimes this can be overkill, it means that you should always consider another way around before using this method, read here, html - Is it considered bad practice to use absolute positioning? - Stack Overflow[^].
 
Share this answer
 
Comments
s yu 6-Jul-16 11:13am    
AAZ: Thanks for your advisory. Your code works partially. In this table, the header row contains 3 cells. I revised your code a little bit,
row.style.position = "absolute";
Then, it works. Thanks again.
Afzaal Ahmad Zeeshan 6-Jul-16 12:00pm    
You can also mark the post as answer.
[no name] 6-Jul-16 14:51pm    
Have a 5 for now :)
Afzaal Ahmad Zeeshan 6-Jul-16 15:21pm    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900