Search code examples
jquerycssjquery-waypoints

Page jumps when sticky navigation appears


I'm trying to add a sticky navigation to a page once you scroll to the first section (About Systemic Therapy).

View webpage here

See code on GitHub here

However, as soon as the sticky navigation appears, the page jumps. This also impacts where the page lands when you click on "Systemic Psychotherapy" in the nav bar. Instead of landing at the top of the section, it covers the heading and the first few sentences. However, this only happens when you click at the top of the page.

I've tried using Waypoints:

$('.js--section-about-st').waypoint(function(direction) {
    if (direction == "down") {
        $('nav').addClass('sticky');
    } else {
        $('nav').removeClass('sticky');
    }
});

And jQuery:

$(window).scroll(function() {
  if ($(this).scrollTop() > 400){
    $('nav').addClass('sticky'); 
   }
  else{
    $('nav').removeClass('sticky');
  }

The size of the navigation bar reduces when it becomes sticky. I've read that this can cause the page to jump, so I've tried keeping it the same size, but it still jumps.

Can anyone please help me work out where I'm going wrong?

Thanks!


Solution

  • When you make an element position: fixed;, it is removed from the flow of the page, meaning it won't affect other elements. Any height that it once occupied is nullified. Here is an example of this behavior.

    The non-sticky navigation is 105px, so when it becomes sticky, all the elements after your navigation will move up 105px to occupy that space. Consider applying that same 105px as padding-top to the <body> to make up for the now-missing navigation bar. Here is the same example from above, but with the fix now in place.

    $(window).scroll(function() {
      if ($(this).scrollTop() > 400){
        $('nav').addClass('sticky'); 
        $('body').css('padding-top', '105px'); //Height of non-stick nav
       }
      else{
        $('nav').removeClass('sticky');
        $('body').css('padding-top', '');
      }
    });