Question

I've got following code for my Header that gets sticky if it reaches the top of the window:

$(function () {
    var stickyHeaderTop = $('#outer-header').offset().top;

    $(window).scroll(function () {
        if ($(window).scrollTop() > stickyHeaderTop) {
            $('#outer-header').css({
                position: 'fixed',
                top: '-300px'
            });
        } else {
            $('#outer-header').css({
                position: 'static',
                top: '0px'
            });
        }
    });
});

It works, but as it reaches the top and gets sticky the content scrolls the normal scroll + the height of the div that was over the Header.(so it makes a too big jump that doesn't look smooth)

Was it helpful?

Solution

Thanks to CBroe for his hint! This is a working solution:

$(function () {
    var stickyHeaderTop = $('#outer-header').offset().top;

    $(window).scroll(function () {
        if ($(window).scrollTop() >= stickyHeaderTop) {
            $('#outer-header').css({
                position: 'fixed',
                top: '-300px'
            });
            $('#main').css({
                position: 'relative',
                top: '332px'
            });
        } else {
            $('#outer-header').css({
                position: 'absolute',
                top: '0px'
            });
            $('#main').css({
                position: 'relative',
                top: '332px'
            });
        }
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top