Content under sticky header jumps on scroll

528 views Asked by At

I have added a div that has a fixed class added to it, and the class is removed when the scroll position reaches 0, but the content under the fixed div jumps and I'm not sure how to fix that.

Here is my HTML structure:

<div class="announcement-wrapper">
    <div class="announcement header-announcement">
         {{ settings.announcement_content_seksy }}
    </div>
</div>

Here is my Vanilla JS:

let scrollpos = window.scrollY
const header = document.querySelector(".announcement")
const header_height = header.offsetHeight


const add_class_on_scroll = () => header.classList.add("fixed")
const remove_class_on_scroll = () => header.classList.remove("fixed")


window.addEventListener('scroll', function() {
  scrollpos = window.scrollY

  if (scrollpos >= header_height) { add_class_on_scroll() }
  else { remove_class_on_scroll() }

  console.log(scrollpos)
})

CSS for the fixed div:

.fixed {
  position: fixed;
  top:0;
  width: 100%;
  z-index: 9999;
}

I have seen similar questions asked but I haven't been able to add anything to fix the content that jumps underneath.

1

There are 1 answers

0
abrosis On BEST ANSWER

Need more context, but from the sounds of it, when you add position fixed, you're taking the announcement out of the context of the page, so it no longer takes up space - it is essentially floating above the other content. This will mean the content will move up to the top.

Once you remove position:fixed, you're adding it back into the page, making it take up height, pushing the content down.

To remedy this, I would just always have the announcement as position fixed and add some padding-top on the parent element the same height as the announcement. Or you could use position:sticky;

https://developer.mozilla.org/en-US/docs/Web/CSS/position