Jimmy
Jimmy

Reputation: 12517

Persistent header causes website to collapse in height

This is my code:

http://jsfiddle.net/KCb5z/8/embedded/result/ http://jsfiddle.net/KCb5z/8/

$(function () {

    var $select = $('#select');
    var $window = $(window);
    var isFixed = false;
    var init = $select.length ? $select.offset().top : 0;

    $window.scroll(function () {
        var currentScrollTop = $window.scrollTop();
        if (currentScrollTop > init && isFixed === false) {
            isFixed = true;
            $select.css({
                top: 0,
                position: 'fixed'
            });
        } else if (currentScrollTop <= init && isFixed === true) {
            isFixed = false;
            $select.css('position', 'relative');
        }
    });

    $(".nav").click(function (e) {
        e.preventDefault();
        var divId = $(this).attr('href');
        $('body').animate({
            scrollTop: $(divId).offset().top - $select.height()
        }, 500);
    });

});

The issue is when I scroll past the yellow bar it changes its CSS from relative to fixed. This means the website is now less tall and it drags all the content up, causing a kind of glitching effect.

It's almost like I need a containing div for the yellow bar which remains to keep that height, or insert some sort of div to keep the website height the same if the bar is docked or not.

Can anyone show me please how this might be implemented?

Upvotes: 1

Views: 46

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337701

When the position is set to fixed, add padding to the top of the body to accommodate it. Similarly, remove the padding when the element is un-fixed:

if (currentScrollTop > init && isFixed === false) {
    isFixed = true;
    $select.css({
        top: 0,
        position: 'fixed'
    });
    $('body').css('padding-top', $select.height());
} 
else if (currentScrollTop <= init && isFixed === true) {
    isFixed = false;
    $select.css('position', 'relative');
    $('body').css('padding-top', 0);
}

Example fiddle

Note, the padding-top can be set on any element above the one to be fixed if required. I just used body as it was the most convenient for an example.

Upvotes: 2

Related Questions