A fixed header for tables that shifts along with horizontal scrolling

Seeking assistance with a persistent issue - I have a table with a fixed header on vertical scroll (see CSS and Javascript below), but the header fails to move horizontally when I scroll.

    window.onscroll = function() {myFunction()};
                var header = document.getElementById('myHeader');
                var sticky = header.offsetTop;
                function myFunction() {
                    if (window.pageYOffset > sticky) {
                        header.classList.add('sticky');
                    } else {
                        header.classList.remove('sticky');
                    }
                }
    .sticky {
                      position: fixed;
                      top: 0;
                      z-index:1000;
                      padding-left:62px;
                      overflow-x: scroll;
                    }


                
    
                <table id='table' class='display cell-border'>  
                                <thead class='head' id='myHeader'>
                                    <tr>
                                        <th class='noSearch'></th>
                                        <th class='noSearch'></th>
                                        <th>Shell ID</th>
                                        <th>Package ID</th>
                                        <th>Package Title</th>
                                        <th>Product Type</th>
                                        <th>Project</th>
                                        <th>Current Phase</th>
                                        <th>Status</th>
                                    </tr>
                </thead>
                    <tr>
                    <td>Shell ID</td>
                                        <td>Package ID</td>
                                        <td>Package Title</td>
                                        <td>Product Type</td>
                                        <td>Project</td>
                                        <td>Current Phase</td>
                                        <td>Status</td>
                            </tr>
              </table>

Would greatly appreciate any guidance on this matter.

Answer №1

Check out this helpful method: https://codepen.io/anon/pen/vVGeVM

<!------------------------------Css-------------------->
.tableContainer{
  overflow: auto;
  height:100px;
}
td, th{
  width:80px;
  text-align:center;
}

<!------------------------html-------------------------->

<table id='table' class='display cell-border'>  
    <thead class='head' id='myHeader'>
            <tr>
                <th class='noSearch'></th>
                <th class='noSearch'></th>
                <th>Shell ID</th>
                <th>Package ID</th>
                <th>Package Title</th>
                <th>Product Type</th>
                <th>Project</th>
                <th>Current Phase</th>
                <th>Status</th>
             <tr>
 </thead>
 <tbody>
   <tr>
    <td colspan="12">
      <div class="tableContainer">
        <table>
          <tr>
            <td>example</td>
             <td>example</td>
             <td>example</td>
             <td>example</td>
             <td>example</td>
             <td>example</td>
             <td>example</td>
             <td>example</td>
             <td>example</td>
          </tr>
        </table>
      </div>
     </td>
   </tr>
 </tbody>
</table>

Answer №3

It appears that you may want to consider avoiding the use of the window.onScroll event and instead rely on CSS to handle this behavior.

   .sticky {
          position: fixed;
          top: 0;
          z-index:100;
        }

Make sure to add the following property to the header's parent element:

 #table{
 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

Unable to make a successful POST request using the JQuery $.ajax() function

I am currently working with the following HTML code: <select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select> along with an: <input type="text" id="prd_price" ...

Navigating with buttons in React JS

In my material-ui, I have a button set up like this: <Button style={green} raised="true" label="Continue to create group"}> CREATE NEW GROUP </Button> I am looking to make it so that when the button is clicked, it will take me ...

The functionality is verified in Postman, however, it is not functioning properly when accessed from my client's end

I am working on a project where I have a button in my client's application that is supposed to delete a document from a MongoDB collection based on its ID. Here is the backend code for this functionality: index.js: router.post('/deletetask' ...

Learn the process of transferring information through ajax while managing dependent drop-down menus

I have successfully set the initial value from the first combo-box and now I am looking to send the second variable from the second combo-box and receive it in the same PHP file. Below is the Ajax code snippet: $(document).ready(function(){ $(".rutas") ...

Photoshop optimized webpage appearing distorted on Internet Explorer after saving for web

I designed a webpage using Photoshop, sliced it, saved it for the web, and uploaded the HTML file. It looks great in Firefox and Chrome, but Internet Explorer tells a different story. Does anyone know how to fix it and why there is this black padding? IE: ...

Use HTML5 to implement canvas dragging functionality

My project involves a large HTML5 Canvas that I need to function similar to Google Maps: the ability for users to drag it and view only a portion of it (equal to the screen size) at any given time. The canvas should render only the visible portion on the ...

Experimenting with Selenium to automate processes involving dynamic class attributes

My issue involves a Button class = "searchbar__SearchButton-sc-1546roh-3 searchbar__CancelButton-sc-1546roh-4 glEceZ" I am attempting to locate this element in the browser using return browser.element('button[class^="searchbar__CancelButton-"]&ap ...

Create a Bootstrap multi-bar component for visually displaying the daytime information

I am looking to create a horizontal bar with multiple intervals. Here is what I have tried so far: <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"& ...

Having difficulty applying capitalization to the initial word in an input using JavaScript/jQuery

I've read through several other discussions on this forum regarding the same issue. My problem lies in capitalizing the first letter of an input. Here is the link to my code on JSFiddle Despite my efforts, I can't seem to get the substr() funct ...

How can I dynamically adjust the font size of content in a React Material-UI Button when it's unexpectedly

In my web application project, I have created multiple choice questions where each answer is displayed within a single button: <Button fullWidth={true} variant="contained" onClick={(answer) => this.handleAnswer(this.state.answers[0].tex ...

There seems to be an issue with the Typescript version compatibility in the node_modules folder for the Angular Material table cell component

While working on my project with Angular, I encountered an issue. I attempted to downgrade my TypeScript version to 3.9.7 but the problem persists. Below are the dependencies listed in my package.json: "private": true, "dependencies&qu ...

What is causing the error in this particular stream function?

I created a function that logs the provided arguments to the console when piped into it. function logToConsole() { var stream = new Stream.Transform({objectMode: true}), args = [].slice.call(arguments); stream._transform = function (data, ...

Using Highstock for Dynamic Data Visualization in Web Applications

Looking to create a chart using data from a MySQL database that includes timestamps and temperature readings. The timestamp format is '2015-06-11 22:45:59' and the temperature is an integer value. Unsure if the conversion of the timestamp to Java ...

When the script is placed at the end of the file, document.getElementById() is still returning null

I need assistance with running a JavaScript function that is located at the end of my .aspx file. This is the div tag in question: <div id="div_NRContainer" oninit="div_NRContainer_Init" class="panelContainer" runat="server"> Following this, with ...

Using Angular 2 to select with default value from a separate model

Is there a way to set the default value or link to another model while utilizing NgFor on a different model? The model intended for binding is as follows: "Bookings": {"dates": [{"date":"3-10-2016","slot":"Full"}, {"date":"4-10-2016","slot":"Full"}, {"da ...

What is the process of caching images when they are loaded through a php script?

My PHP script acts as a random image generator by querying the database for user images and returning a random one. Below is the code snippet responsible for serving the randomly chosen image. header('Content-Transfer-Encoding: binary'); header( ...

Different ways to create audio using GWT

Looking for ways to incorporate audio into your GWT app? I am considering creating a simple game, but it seems like there hasn't been much progress on direct audio support within GWT. This is likely due to the lack of underlying browser support, but I ...

"AngularJS offers a unique way to include alternative text in placeholders and titles using

I need to implement an input field (<input..>) with a placeholder and title for tooltip that functions in the following way: There is a variable called "myString" which can either be undefined/empty or contain a string. When empty, a default string ...

Troublesome Issue with ngAnimate and ngHide: Missing 'ng-hide-animate' Hook Class

I am working on a case where I need to add animation to a DOM object using the ngHide directive: Check out this example here Within this scenario, I have an array of JSON objects: $scope.items = [ {"key": 1, "values": []}, {"key": 2, "values": [ ...

Align two columns using the vertical alignment feature in the Bootstrap grid system

Is there a way to horizontally align an element within a bootstrap grid? In the code snippet below, I have a col-md-4 and another col-md-8 that I would like to vertically align in the middle, as shown in the image. Click here for a demonstration. This is ...