Home > database >  ScrollY is shaking?
ScrollY is shaking?

Time:08-15

So sorry to bother you but I have an issue that I can't overcome.

Here's the point :

I have an header in sticky position and I want the header to reduce his height once passed 50px scrolled. The problem is that as soon as I scroll down the page, my scrollY value keeps going under 50 and over 50 :

Scroll value changing

So my header just won't stay in his 'scrolled' event or in his 'unset' event.

Here's my code :

JS :

let header = document.querySelector('.header');
let img = document.querySelector('.headerImg');
let logo = document.querySelector('.logo');

window.addEventListener('scroll', () => {
   if (window.scrollY > 50) {
      header.classList.add('scrolled');
      img.classList.add('imgScrolled');
   } else{
      header.classList.remove('scrolled');
      img.classList.remove('imgScrolled');
   }
});

CSS :

.header{
    width: 100%;
    height: 334px;
    max-height: 334px;
    overflow: hidden;
    transition: max-height 0.3s cubic-bezier(0, 1, 0, 1);
    transition: max-height 0.3s ease-in-out;
    background-image: url(../../view/assets/img/header1.jpg);
    background-position: center -664px;
    background-repeat: no-repeat;
    background-size: cover;
    display: flex;
    justify-content: center;
    align-items: center;

}

.scrolled{
    max-height: 141px!important;
    transition: max-height 0.3s cubic-bezier(0, 1, 0, 1);
    transition: max-height 0.3s ease-in-out;

}

.imgScrolled{
    width: 15%!important;
    transition: width ease-in-out 0.3s;
}

.header img{
    width: 40%;
    transition: width ease-in-out 0.3s;
}

HTML :

  <nav>
        <div >
            <img src="view/assets/img/logoTxtVert.png" alt="" >
        </div>

  </nav>

I can't show it but it results in my header litteraly shaking...

If you can help... TY !

(Sorry for my english, tried my best)

CodePudding user response:

Use document.body.scrollTop to get the value of px from top it has scrolled

window.addEventListener('scroll', () => {
  if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
    header.classList.add('scrolled');
    img.classList.add('imgScrolled');
  } else {
    header.classList.remove('scrolled');
    img.classList.remove('imgScrolled');
  }
});

CodePudding user response:

It's because your header is effecting the overall size of the page, so as you reach 50% the header shrinks, which in turn shrinks your overall page size, which then puts you at less than 50% scroll which increases your header size which...

There are many solutions to this depending on why you're shrinking it, but you can do any of these (or more):

  • put the header in a container with a fixed height
  • give them an absolute position
  • give them a fixed position
  • change the top and bottom padding instead of the height

anything to prevent the overall HTML height from changing, and it should stop the shaking.

  • Related