"Table featuring rows that can be scrolled and a header that remains fixed in

I have implemented this code using this solution, but unfortunately, it doesn't seem to be working as expected.

My requirements are :

  • Scroll through the rows
  • Keep the header fixed
  • Ensure that the headers width matches the first TD row.

Being new to JavaScript, I am struggling to identify what might be missing. While the scrolling part is functioning properly, it's not replicating in jsfiddle. How can I achieve the same width for both TH and TD?

EDIT 1 :

Code

<html>
<head>
    <style>
        .outerDIV {
            position: relative;
            padding-top: 30px;   //height of your thead
        }
        .innerDIV {
            overflow: auto;
            max-height: 200;       //the actual scrolling container
        }
        table thead {
            display: block;
            position: absolute;
            top: 0;
            left: 0;
        }
        table tbody {
            display: block;
        }
    </style>
    <script>
        function scrollingTableSetThWidth(tableId)
        {
            var table = document.getElementById(tableId);

            ths = table.getElementsByTagName('th');
            tds = table.getElementsByTagName('td');

            if(ths.length > 0) {
                for(i=0; i < ths.length; i++) {
                    ths[i].style.width = getCurrentComputedStyle(tds[i], 'width');
                }
            }
        }

        function getCurrentComputedStyle(element, attribute)
        {
            var attributeValue;
            if (window.getComputedStyle) 
            { // class A browsers
                var styledeclaration = document.defaultView.getComputedStyle(element, null);
                attributeValue = styledeclaration.getPropertyValue(attribute);
            } else if (element.currentStyle) { // IE
                attributeValue = element.currentStyle[vclToCamelCases(attribute)];
            }
            return attributeValue;
        }
    </script>

</head>
<body>
    <div class="outerDIV">
        <div class="innerDIV">
            <table border="1">
                <thead>
                    <tr>
                        <div><th>Column1</th><th>Column2</th><th>Column3</th></div>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>Line1Cell1</td><td>Line1Cell2</td><td>Line1Cell3</td>
                    </tr>
                    <tr>
                        <td>Line2Cell1</td><td>Line2Cell2</td><td>Line2Cell3</td>
                    </tr>
                    <tr>
                        <td>Line3Cell1</td><td>Line3Cell2</td><td>Line3Cell3</td>
                    </tr>
                    <tr>
                        <td>Line4Cell1</td><td>Line4Cell2</td><td>Line4Cell3</td>
                    </tr>
                    <tr>
                        <td>Line5Cell1</td><td>Line5Cell2</td><td>Line5Cell3</td>
                    </tr>
                    <tr>
                        <td>Line6Cell1</td><td>Line6Cell2</td><td>Line6Cell3</td>
                    </tr>
                    <tr>
                        <td>Line7Cell1</td><td>Line7Cell2</td><td>Line7Cell3</td>
                    </tr>
                    <tr>
                        <td>Line8Cell1</td><td>Line8Cell2</td><td>Line8Cell3</td>
                    </tr>
                    <tr>
                        <td>Line9Cell1</td><td>Line9Cell2</td><td>Line9Cell3</td>
                    </tr>
                    <tr>
                        <td>Line10Cell1</td><td>Line10Cell2</td><td>Line10Cell3</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>

Answer №1

If your scrolling function is not working, it might be due to the lack of units on the max-height property of your .innerDiv.

To align the width of the header with the table, you can achieve this without the need for javascript by setting the width of the <th> and <td> cells using CSS.

Take a look at this example: http://jsfiddle.net/MVxZb/10/

UPDATE: I have corrected the link and removed any unnecessary javascript from the code.

Answer №2

Your issue is not with JavaScript but with HTML formatting. To resolve the problem, you should separate your header and table into two different containers instead of grouping them together under the same container (tbody).

<div style="width:200px">
 <table style="width:100%">
     <tr><th>header</th></tr>
 </table>
<div>
<div style="width:200px; height:100px; overflow:auto">
    <table style="width:100%">
      <tr>
        <td>value</td>
      </tr>

    </table>
<div>

This can be seen in the example provided here.

Answer №3

Ensure you assign a specific width to an element set in absolute position.

To enhance the appearance, consider making the width approximately 1 em smaller (approximately the average width of a scrollbar).

If you want all columns to have equal width, you can implement something similar to this: http://jsfiddle.net/MVxZb/9/

.outerDIV {
    position: relative;
    padding-top: 30px;
    display:inline-block;
}
.innerDIV {
    overflow: auto;
    max-height: 150px;
    padding-right:1.1em;
    margin-right:-1.1em;
}
table thead {
display:table;
    width:100%;
    border:solid 1px gray;
    box-sizing:border-box;
    position: absolute;
    border-bottom:0;
    top: 0;
    left: 0;
    right:0;
}

You can utilize table-layout:fixed; to evenly distribute the width across your columns if neither th nor tds have a specified width.

Answer №4

When I wanted to ensure the header of a table stayed in place, this was my go-to solution. I'm open to exploring other alternatives as well.

Feel free to check out the demo.

table th,
table td {
    padding: 10px;
    width: 100px;
}

.fixed-header{
    position: fixed;
    background: #fff;
}
.container{
    height: 402px;
    overflow: auto;
}

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

Issue with updating Parent value in Vue component when Child value changes

I am working with an Array to fill a Dialog Vue Component. My setup looks like this: basicInfo: [{ firstName: "John" , lastName: "Doe" }], <basicInfoForm v-model="showBasicInfoForm" :basicInfo="newbasicInfo[0]"></basicInfoFo ...

Tips for adjusting the height of the Bootstrap navbar and ensuring the text remains centralized

I've attempted various methods to customize the Bootstrap navbar. I have successfully changed its color and adjusted its height. However, there is still an issue with the text alignment.Check it out here. ...

Is it possible to implement a route within a controller in Express.js?

In my controller, I currently have the following code: module.exports.validateToken = (req, res, next) => { const token = req.cookies.jwt; //console.log(token); if (!token) { return res.sendStatus(403); } try { const ...

Tips for incorporating CRUD functionality using jQUery

Recently, I successfully created a users list using CRUD with PHP, MySQL, and Bootstrap. Everything was working smoothly. However, I faced some errors when trying to integrate jQuery to avoid page refreshes during operations. Creating/inserting new users ...

Having trouble getting static serving to work on Express.js when custom middleware is added

Seeking assistance with creating a middleware for my express js website to incorporate subdomains and serve static image, css, and js files. While my HTML pages load properly, I encounter long page load times and the javascript files fail to load. Any gui ...

How to open a link in the URL bar of Safari on iOS using JavaScript

My goal is to open a link through the iOS Safari address or URL bar. After testing, I have found that in newer iOS versions, the address bar no longer executes javascript:alert("hi"); as it did before. Have any new methods been introduced, or h ...

Safari and iOS users may not experience the onended() event triggering

Code snippet performs as expected on Chrome 80.0 and Firefox 74.0 (OSX 10.14.6). However, when testing on OSX Safari 13.0.5 or iOS (using Chrome, Safari), the <div> element fails to turn blue, suggesting that the onended callback is not triggering. C ...

Retrieve the names of items from an array and generate an unsorted list

var Info = [ {"Different Parts of Story" : [ {"NSP" : "Netting Systemically Potent"}, {"PNK" : "Polar Necessary Climate"} ]}, {"Physics and More" : [ {"SZK" : "Snowy Z from Crossing"}, {"ZZS" : "Zone of Software ...

What is the best way to incorporate annotations onto a website without impacting the overall design and layout?

I'm currently working on a personal project that is similar to markup.io where users can load any website and add annotations. I am struggling to implement an annotation feature that functions like the one in markup.io: Does not disrupt the styling o ...

To properly conduct Playwright Component testing, it is essential to utilize the defineConfig() function

Currently, I am utilizing Playwright to execute tests on my components. The installation of playwright was completed by using the following command: npm init playwright@latest -- --ct Below is the configuration file for playwright-ct: import { defineConf ...

How do webpack imports behave within a ReactJS project?

In my ReactJS project, I have utilized various 3rd party libraries such as lodash, d3, and more. Interestingly, I recently discovered that I did not explicitly write imports like import d3 from 'd3' or import _ from 'lodash' in all of ...

Steps for changing an object into an array

I need help converting an object into an array using pure javascript. Here is the object I want to convert: [{"itemCode":"Mob-mtr"},{"itemCode":"640-chr"}] This is how I want the array to look like: ["Mob-mtr","640-chr","541-mtr"] I've attempted ...

Displaying unique input values with ng-model

Within the controller, there is a variable that monitors the page index (starting at 0) for a paginated table: var page { pageNumber: 0; } Query: How can I display this pageNumber variable in the HTML, but always incremented by +1? (since the index=0 p ...

Creating a banner using four grid elements, with each element containing four child elements, is a simple process that can

Can you assist me in recreating my idea from an image? I am having trouble understanding how to select and place other elements, and then return them to their original positions after deselecting... I attempted to use a grid but it did not work properly. ...

Guide on serializing an object containing a file attribute

I'm currently working on creating a small online catalog that showcases various housing projects and allows users to download related documents. The data structure I am using is fairly straightforward: each project has its own set of properties and a ...

Having difficulty coming back from a promise catch block

I'm struggling to populate a menu list from my PouchDB database because I am unable to retrieve anything within the promise that is executed after calling get on the db. Below is the code in question: <MenuList> {this.populateSavedClues()} ...

Adjusting the slider with jQuery and CSS to extend beyond 100% while remaining within the div boundaries

Currently, I'm working on customizing a jQuery slider. My goal is to achieve the same functionality as the jQuery UI slider where you can set a max value like "2500" and the slider will smoothly adjust without going outside of the specified div or scr ...

Incorporating images into CSS using an npm package

My npm package has the following structure: --src --styles -image.png -style.scss In the style.scss file, the image is referenced like this: .test { background-image: url(./image.png); } The issue arises when consuming the package, as th ...

Using JavaScript to retrieve comma-separated values depending on a specific condition

Hey there, I am encountering a problem with filtering out values from an array of objects. Essentially, I have an array of objects const arr = [ { "id": null, "name": null, "role": "Authorized ...

A different and more efficient way to address the issue at hand

During a recent interview, I was asked the following question and despite being able to solve it, the interviewer pointed out that my code was not optimized. Is there anyone who can help me with an optimized solution? Question : Given an array array1, rea ...