0

There are a few posts on this already, and one answer that addresses the glitch I'm experiencing but the fix doesn't work with my setup. (Existing Post 1) (Existing Post 2)

-

I've used some JS to create a div that sticks to the top of the browser window when a user scrolls past it. The setup works by applying the class .sticky to the existing parent container #stickywrapperaa when a user scrolls past the parent element. Here is the JS:

<script>
jQuery(document).ready(function( $ ) {
   // Cache selectors outside callback for performance. 
   var $window = $(window),
       $stickyEl = $('#stickywrapperaa'),
       elTop = $stickyEl.offset().top;

   $window.scroll(function() {
        $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
    });
});
</script>

This creates the element ID/class attribute of #stickywrapperaa.sticky which I have then positioned and styled using CSS. All of this so far is working.


The problem:

The problem I have is that when the sticky header is activated this removes a section of the page height and causes the static page content to jump up by the same height as the parent container (#stickywrapperaa).

Logically this makes perfect sense as the container has been moved ontop of the static page content so it's now missing from the page content; however this leaves a gaping hole in my page that I now need to fill.

I thought about creating an empty space of equal height to the parent container (#stickywrapperaa) and triggering that to appear with the sticky class, effectively replacing where the header used to be with an empty space.

Can anyone help me achieve this or provide a better solution?

Community
  • 1
  • 1
  • Add a padding-top to body when you toggle the sticky class. The padding should be the same height as your header. – cjs1978 May 15 '17 at 11:32

2 Answers2

0

Set the position of the div that gets removed to absolute, while creating another, invisible div that is set to relative, and has the same height as the absolute div.

Although adding in the div with the height later might work, it would overly complicate things when you could just put it there in the first place, and remove the visible div from the normal flow.

LJD
  • 498
  • 4
  • 11
0

Add a padding-top to body when you toggle the sticky class. The padding should be the same height as your header.

<script>
jQuery(document).ready(function( $ ) {
   // Cache selectors outside callback for performance. 
   var $window = $(window),
       $stickyEl = $('#stickywrapperaa'),
       elTop = $stickyEl.offset().top;

   $window.scroll(function() {
        $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
        if ($window.scrollTop() > elTop){
            $("body").css("padding-top", $stickyEl.height());
        } else {
            $("body").css("padding-top", 0);
        }
    });
});
</script>
cjs1978
  • 477
  • 3
  • 7