Subheaders that stay in place while scrolling through a table with a stationary header

My goal is to design a table with a fixed header that allows the body to scroll under the header. While this is a common design, I am facing the challenge of implementing sticky subheaders. These subheaders should scroll along with the table until they reach the fixed header, at which point they should remain static until the rest of the section has scrolled beneath them, and then be swapped out with the next sticky subheader (similar to the iPhone address book). For reference, here's an example of the desired outcome: Getting a sticky header to "push up", like in Instagram's iPhone app using CSS and jQuery

While the example provided isn't based on a table, I need to display a large amount of tabular data, so the design must involve a table structure. I have searched for existing examples of this functionality but have been unsuccessful. I have also included a link to a jsfiddle example without fixed headings to prevent conflicts with other solutions: https://jsfiddle.net/q7zLhus0/

<table>
<thead>
    <th>A</th>
    <th>B</th>
    <th>C</th>
    <th>D</th>
    <th>E</th>
</thead>
<tbody>
    <tr>
        <th class="subheader" scope="rowgroup" colspan="5">Data group 1</th>
    </tr>
    <tr>
        <td>1</td>
        <td>6</td>
        <td>3</td>
        <td>6</td>
        <td>2</td>

    </tr>
    ...

I would greatly appreciate any assistance in achieving this design. It has been a challenging problem for me to solve.

Answer №1

Include This Feature

function stickyHeaders(headers) {

        var thatObj = this;

        thatObj.initialize = function () {

            headers.each(function () {

                var thisHeader = jQuery(this).append('<span class="test" />');
                thisHeader.parent().height(thisHeader.outerHeight());

                jQuery.data(thisHeader[0], 'pos', thisHeader.offset().top);

            });

            jQuery(window).off("scroll.headers").on("scroll.headers", function () {

                thatObj.onScroll();

            });
        }

        thatObj.onScroll = function () {

            headers.each(function (i) {

                var thisHeader = jQuery(this),
                    nextHeader = headers.eq(i + 1),
                    prevHeader = headers.eq(i - 1),
                    position = jQuery.data(thisHeader[0], 'pos');

                if (position <= jQuery(window).scrollTop()) {

                    thisHeader.addClass("fixed");

                    if (nextHeader.length > 0 && thisHeader.offset().top >= jQuery.data(nextHeader[0], 'pos') - thisHeader.outerHeight()) {

                        thisHeader.addClass("absolute").css("top", jQuery.data(nextHeader[0], 'pos') - thisHeader.outerHeight());
                    }

                } else {

                    thisHeader.removeClass("fixed");

                    if (prevHeader.length > 0 && jQuery(window).scrollTop() <= jQuery.data(thisHeader[0], 'pos') - prevHeader.outerHeight()) {

                        prevHeader.removeClass("absolute").removeAttr("style");
                    }
                }
            });
        }
    }

    jQuery(document).ready(function () {

        new stickyHeaders(jQuery(".header")).initialize();

    });

Example Link -https://jsfiddle.net/kjo9w57a/1/

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

Angular - creating a specialized input field for a unique MatDialogConfig configuration file

I have a unique setup with a custom MaterialDialogConfig file dedicated to handling all of my material dialog components. Here's what the configuration file looks like: import { MatDialogConfig } from "@angular/material"; export class MaterialDialog ...

Detecting the presence of an object in JavaScript or jQuery

My current code is able to save the HTML content of clicked divs in localStorage and then append it to the #result div when the 'Saved Events' button is clicked. However, I am facing a challenge where I need to check if objects already exist in # ...

iOS device encounters failure with Ajax CORS request and redirect

I am experiencing an issue where a URL is being redirected to another domain by the server. My test code is very simple: $.ajax({ type:"GET", url:"{MYURL}", success:function(d){alert('response');} }) You can che ...

Where is the ideal location to store non-component data properties in Vue.js?

Currently, I am in the midst of a Vue.js project where components are predominantly used. However, there are moments when I simply need to incorporate some Vue.js syntax without creating an entire component. Since I am not utilizing the render function as ...

Tips for effectively utilizing MeteorPad: (Note: ensure to use at home instead of at work due to potential firewall or proxy issues)

UPDATE: It's possible that the issue is related to a firewall or proxy. MeteorPad doesn't work at my workplace, but it works fine at home. I've been attempting to use MeteorPad () but I'm encountering some difficulties. The bottom are ...

Is it possible to output the value of history.go(-1) using a print function?

Currently, I'm working on enhancing a Vue application. My goal is to retrieve the value of the previously visited page using history.go(-1) and then use that value to assign certain values to a variable. This is what I have in mind: <script> ...

Tips for applying unique CSS classes to individual templates in Joomla

I manage a website at www.kadamjay.kg using an RT template system where each language version has its own unique template. However, when I add a class to a specific element, it only changes on one template and there are no additional templates in the pat ...

Incorporating a requirement into a function to ensure it is executed only under certain circumstances

I'm currently developing a text-based game using JavaScript that involves picking up a sword with the help of an in-game function. var takeSword = function() { if (currentRoom.hasSword) { $("<p>You picked up a sword.</p&g ...

Tips for creating responsive text within a hero image

I'm exploring the world of creating responsive websites using Bootstrap, a new venture for me. One challenge I've encountered is trying to create a hero image with text positioned perfectly in the center. Despite my efforts, the text does not adj ...

Vue fails to detect changes in an Array

Hey everyone, I'm currently working on a Vue project and I have been attempting to create a recursive tree from a flat list. My goal is to toggle the expanded property of each item when clicked, but for some reason, it's not updating. The issue ...

What is the method for loading a subcategory based on the category by invoking a jQuery function within the <td> element of a JavaScript function that adds rows dynamically?

Whenever I click the add row button, the category dropdown list successfully loads. However, when I select an option from this category list, the subcategory does not load any list. The Javascript function responsible for adding rows dynamically is as fol ...

I'm having trouble accessing the outcome from within the function

Having trouble getting the result to return inside a function for my basic rock paper scissors game. I've tried everything, including console logging the compare and putting it inside a variable. Strange enough, console.log(compare) is returning und ...

Achieving dynamic HTML element addition through JavaScript while maintaining their record in PHP

There is an input box where the user specifies the number of new DIV elements to be added dynamically. This request is then sent to PHP via Ajax, where it prepares an HTML DIV with some inner input tags. Each DIV has a unique id attribute generated increme ...

HTML structure consisting of a 3 by 3 grid

Creating a 3x3 grid with cells that have varying heights depending on content is proving to be challenging. Except for the cells marked with red arrows, the rest of the grid has fixed height in pixels. I attempted to build a 3x3 grid using divs to experi ...

How can we track and record NaN values in JavaScript/TypeScript as they occur in real-time?

Is there a reliable method to identify and prevent NaN values during runtime, throughout all areas of the application where they might arise? A) Are there effective linting tools available to alert about possible occurrences of NaN values within specific ...

Sending a document through the input field with React Hook Form

In my application, I have implemented a file input to submit a file and send it to a firebase storage bucket. To achieve this functionality, I am utilizing the react-hook-form library. However, I encountered an issue - I wanted the file to be uploaded with ...

JavaScript's innerHTML property is failing to update

Hello there, I am currently attempting to update the innerHTML content of the script below: <div id="global-alert-queue" class="layout-wrapper"> <div class="alert success animate-in" role="alert"> Your submission was successful. <button i ...

Concealing a column in ngx-datatable Ionic

I am just starting to work with NGX-datatable and I need to populate my data table in my Ionic app with data from Firebase. Here is the format of the JSON returned from Firebase: If I choose not to use the User_id as a column, how can I access the User_id ...

I'm encountering an issue with numbers that contain comma decimal separators

My current script is designed to calculate the amount of water saved by a shower column. However, I have encountered issues with its functionality in Firefox and Edge when switching between using "," and "." for values interchangeably. I have attempted va ...

Adjust the color of additional SVG paths upon hovering

I have the following code snippet. .icon {stroke-width: 0; stroke: currentColor; fill: currentColor;} a {color: red} a:hover {color: pink} a:hover circle {fill: green !important; color: orange} a:hover path {fill: blue !important} <a href=""> ...