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>