Ensure the table header in Django tables2 remains fixed at the top of the page as you scroll

Looking for a way to make tables in Django using django-tables2 stick to the top of the page as you scroll down? Check out some relevant code snippets below:

tables.py

class Example(tables.Table):
    field1 = tables.Column()
    field2 = tables.Column()
    field3 = tables.Column()

    class Meta:
        attrs = {'class': 'table table-striped', 'style': 'display: block; overflow: auto;'}

example.html

<style></style>
<table>
    <thead>
        <tr>
            <td>Field1</td>
            <td>Field2</td>
            <td>Field3</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Text</td>
            <td>Text</td>
            <td>Text</td>
        </tr>
    </tbody>
</table>
<script></script>

Struggling with getting the headers to stick after scrolling with CSS and JavaScript? Share your solutions or ask for help - I'm using jquery-3.2.1. Thanks!

Answer №1

Consider implementing the following code snippet:

window.onscroll = function() {
  myFunction()
};

var navbar = document.getElementsByTagName("table")[0];
var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
.sticky {
  position: fixed;
  top: 0;
  width: 180px;
  margin: auto;
  background: white;
}

.sticky+tbody {
  padding-top: 60px;
}

table {
  table-layout: auto;
  width: 180px;
  margin-top: 20px;
}

table,
th,
td {
  border: 1px solid black;
}

table.one {
  margin-bottom: -20px;
}
<table class="one">
  <thead>
    <tr>
      <td>Field1</td>
      <td>Field2</td>
      <td>Field3</td>
    </tr>
  </thead>
  <tbody> </tbody>
</table>
<table class="two">
  <tbody>
    <tr>
      <td>Text</td>
      <td>Text</td>
      <td>Text</td>
    </tr>
    <!-- Additional table rows and data -->
  </tbody>
</table>

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

Enhancing ajax content with Rx.Observable.fromEvent: A step-by-step guide

I am currently fetching content using Ajax, in the form of a json object, which is then displayed in the browser. var stateSubjectSub = stateSubject.subscribe(function(data) { console.log('state changes'); console.log(data); var list = document ...

What is the correct way to update an array of objects using setState in React?

I am facing an issue where I have an array of objects that generates Close buttons based on the number of items in it. When I click a Close button, my expectation is that the array should be updated (removed) and the corresponding button element should dis ...

Updating a view based on a value entered prior to submitting the form in MVC/C# - a complete guide

I'm working on a simple view that displays start and end dates. My goal is to show a "Half Day" checkbox only if the start date matches the end date. So far, I've attempted to implement this feature, but the view isn't refreshing as desired ...

Changing the color of a div's text based on its content with CSS

I am facing a challenge in styling the text inside a “div” element using a Javascript function. Initially, when the page loads, these “divs” contain no value. The values of the "divs" will change between "Open" and "Closed" twice a day when the Jav ...

Encountering a problem while trying to run npm publish with public access, error code E

I've encountered an issue when attempting to publish a scoped package on npm, where I consistently receive this error via the CLI: npm ERR! code E403 npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/@username%2fdynamic-ui-elements - Forbidd ...

Is the aspx page object linked to a MasterPage object page item?

Having trouble with a drop-down menu in my MasterPage file that keeps dropping behind objects on the ASPX page. I've tried using CSS to set different z-index values and position attributes, but it's not working as expected. Is this even possible ...

The HTTP POST function of the controller is failing to trigger when attempting to use the AJAX method

I am trying to create a basic search page where the results are displayed upon clicking the search button. View: @model MvcSearchEngine.Models.SearchResultsModel @{ ViewBag.Title = "Index"; } <script src="~/Scripts/jquery-1.8.2.min.js" type="text/ ...

Experiencing difficulties when integrating the pdf-viewer-reactjs module within Next.js framework

I recently integrated the pdf-viewer-reactjs library into my Next.js project and encountered the following error: error - ./node_modules/pdfjs-dist/build/pdf.js 2094:26 Module parse failed: Unexpected token (2094:26) You may need an appropriate loader to h ...

Is it possible for React Server Side rendering to be re-rendered on the client side?

In this demonstration of isomorphic rendering found at https://github.com/DavidWells/isomorphic-react-example, the author showcases Server Side Rendering by disabling Javascript. However, if JavaScript is enabled on the frontend, does it trigger a re-rende ...

A guide to downloading files through your web browser

Currently, I am working on a project to download videos from the browser using youtube-dl for educational purposes. I have encountered an issue regarding downloading local mp4 files in the browser using axios. The download starts successfully; however, af ...

Troubleshooting the issue: Incompatibility between jQuery .focus() and dynamically generated list items from ng-repeat in AngularJS

I am currently working on enhancing the keyboard accessibility of a website, specifically focusing on making a dropdown menu accessible via keyboard. I am attempting to establish focus on the element with the id= list-0. Below is the HTML code snippet: & ...

The Ajax functionality seems to be malfunctioning when attempting to call a

Required Tasks : I have successfully developed an HTML page with the functionality to store a group of form fields into a separate file. Utilizing the Ajax function (AjaxLoad), I am able to send data to file.php and save it successfully. Although I ...

Make the source transparent to allow the background to shine through

Is there a way to make the source image of an img tag transparent, allowing the background image to show through? For example, if I have this html: <img src="my_image.jpg" height="200" width="300" style="background:url(img/bg.jpg) repeat;" /> I am ...

Are routes in Next.js easy for search engines to crawl?

Currently, I am developing a movie application using NextJS to enhance my skills. The homepage features each movie's title and a brief description. When a user clicks on a movie, they are taken to a dedicated page that showcases more details about the ...

Updating React state manually before using the setState function

Currently, I'm delving into React JS and working on a basic todo list project. A snippet of my code looks like this: changeStatus(e, index) { this.state.tasks[index].status = e.target.value; this.setState((prevState) => ({ tasks: p ...

tips for showing inlinesvg in internet explorer 8

Can anyone assist me with displaying inlinesvg polygons with links in IE8? Is there a jQuery script or any other solution available? <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width= ...

How can you effectively demonstrate that an HTML element is currently being loaded using AJAX?

At times, my application faces the issue of numerous elements loading simultaneously. To address this, I aim to display a customary AJAX spinner above the control (or DOM node) while it remains disabled. What would be the most convenient and effective app ...

Error encountered during EJS compilation

I've encountered a frustrating error while attempting to include an if statement within a forEach loop. My goal is to prevent the delete button from appearing for the currently signed-in user's name (e.g., preventing the deletion of their own ac ...

Search for a specific folder and retrieve its file path

Is there a way for me to include an export button on my webpage that will allow users to save a file directly to their computer? How can I prompt the user to choose where they want to save the file? The button should open an explore/browse window so the ...

I am facing an issue in React Native where components disappear when I update my state. How can I fix this problem?

const DetailedSearchScreen=({ navigation })=> { const mydefauthor='no'; const mydeftitle='data'; var [dataset, setDataset]=useState({data:[{Author:'Deneme', Title:'yapiyorum'}]}); return ( <ScrollVi ...