What's the best way to create sticky headers that stay fixed when scrolling through them?

I'm having trouble making my sticky header work for each element with the .header class. The current code only seems to apply it to the first element. Can someone help me adjust the code so that this effect works for every element with the .header class?

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

var headers = document.querySelectorAll(".header");
headers.forEach(header => {
    var sticky = header.offsetTop;

    function myFunction() {
        if (window.pageYOffset > sticky) {
            header.classList.add("sticky");
        } else {
            header.classList.remove("sticky");
        }
    }
});
html,body,h1{
  padding:0px;
  margin:0px;
}

.header{
  border:1px solid red;
}

.sticky {
  position: fixed;
  top: 0;
  width: 100%;
  background:white;  
}

.sticky + .content {
  padding-top: 102px;
}
<h1 class="header">title1</h1>
<div class="content">
...
</div>

Answer №1

No JavaScript is required for achieving this feature. Simply apply the CSS property position: sticky; with top: 0 to the .header class. Ensure that you also set the background color to white to prevent text overlapping.

Check out the code in this jsfiddle link: https://jsfiddle.net/wmL71xqu/2/

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

managing jquery AJAX requests recursively, signaling completion to the browser

I have a situation where I need to continuously fetch data from an endpoint using a next token if there are more items available. The code snippet below illustrates how I'm currently fetching the data: function get_all_entities(campaign_id, page){ ...

How can I invoke TypeScript methods within a jQuery event handler in the ngAfterViewInit lifecycle hook?

I am currently utilizing Angular 4. I need to invoke methods from a typescript file within the ngAfterViewInit method. declare var $; @Component({ selector: 'app-details', templateUrl: './details.component.html', styleUrls: [&apo ...

Pausing a video when it is not in view

My query is inspired by this one: Is there an event listener for when elements become visible? I am looking to have a video element start playing automatically when it becomes visible and stop when it becomes invisible. This element is a slide within a c ...

Why is it that this JavaScript isn't working as intended in the popup form?

</br> s_foot"> * use ajax.jquery as control event. like $("#save").click(function(){.....}); <script type="text/javascript>" var wp; var position; var pid; var product_name; var production_date; In this script, I am attempting to re ...

Analyzing the latest "barchart.com" website

Is there a way to extract data daily from barchart.com, specifically the close/open/high prices? I can't find the values in the page code or the JavaScript script that loads it. Maybe downloading the Excel file using the "download" button is easier, b ...

What is the method for obtaining the dimensions of a shape drawn on Google Maps?

Is there a way to retrieve the dimensions of a shape drawn using the Google Maps API? I would like to obtain the measurements and include labels on top of the shape. Take a look at this image for reference The event argument in the overlay event does no ...

The power of Three.js comes alive when utilizing appendChild and returning elements

I recently encountered an interesting issue that I managed to resolve, but out of sheer curiosity, I would love for someone to shed some light on why this problem occurred. Below is the snippet of my HTML code: <!DOCTYPE html> <html> < ...

Is it not possible for calc to determine the width of the parent div?

body{width:400px;} .bd{ padding:0 50px 0 80px; height:100px; } .middle{ float:left; width:100%; height:80px;background:blue; } .left{ float:left; width:180px; height:80px;background:#0c9;margin-left:-320px;} <div class="bd"> <div class="mid ...

Having trouble transferring a PHP string to jQuery

I recently set up a script on my computer that displays a list of active interfaces: $ interfaces eth0 lo wlan0 Now, let me share my PHP code snippet with you: <?php $output=shell_exec('./interfaces'); $string = trim(preg_replace(&ap ...

When sending an array through AJAX, make sure you are not missing any form data

I've been working on posting an array using AJAX with the code below, but I'm having trouble seeing a Form Data section in the Headers when checking console. $(document).on("click", "#saveB", function () { var qry_array = []; var qry = q ...

Migrating from jQuery to Vue: Resolving Uncaught TypeError - n.getClientRects is not a valid function

How do I convert this jquery code into Vue.js format? // Scale the cell item. $(document).on('click','.cell-item a', function(event) { event.preventDefault() var $this = $(this) console.log($this) // [a] - correct v ...

The localStorage API (getItem/setItem) is not supported with setTimeout

I find it fascinating how these two codes exhibit different behaviors. It's interesting to note that functions like 'console.log' would work in both scenarios, but localStorage API functions such as getItem and setItem do not. setTimeout(()= ...

Is it possible to utilize a single Promise multiple times?

// App.js sites[site_name].search(value).then(function(results) { console.log(results); }); // SearchClass.js Search.prototype.search = function(search) { var self = this; this.params['wa'] = search; return new Promise(function ...

What is the process for binding an absolute path instead of a relative path in a script that includes Node and Perl calls?

In my script, there is a function with the following code: def tokenize(latex,kind='normalize'): output_file = './out.lst' input_file = './input_file.lst' cmd = "perl -pe 's|hskip(.*?)(cm\\|in& ...

Is it possible to utilize the lighten css property within ngStyle in Angular?

Having some trouble with the lighten property in ngStyle and it's not working as expected. I have a color variable within my component that I want to utilize like so: <div [ngStyle]="{color: schedule.group.color, background: 'lighten(' ...

Length Indeterminate - Pug, Express, and MongoDB

I keep encountering a persistent TypeError message stating that the length is undefined in the following code snippet. This issue is quite frustrating, especially since I've utilized the same code elsewhere in my project without any problems. users.j ...

React - Error: you have a syntax problem because there is an unexpected token <

I am working on a project using Express, pg, and react. However, I have encountered some issues with React. Here is the directory of my project index.js var express = require('express'); var server = express(); var path = require('path&ap ...

Update the table seamlessly to display fresh new data without the need to reload the entire page

I'm looking for a way to display recently added data on a listing page without having to reload the entire page. Currently, I have to refresh the page each time I add new data to my database in order to see the updates. Is there a way to view the new ...

Switching videos dynamically with JavaScript while utilizing Bootstrap to enable playback in a floating window

This is a piece of code that enables playing videos in floating windows using Bootstrap. However, I am looking to enhance the functionality by dynamically changing the video source using JavaScript. I tried using onClick() to modify the src attribute of th ...

The ExpressJS Req.method TypeError occurs when attempting to read the 'method' property of an undefined object

My node express server is throwing an error: Error in index.js. const bodyParser = require('body-parser'), express = require('express'), path = require('path'); const config = require('./config'); con ...