Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling sticky header jumping

Tags:

html

jquery

css

I'm creating a header that'll stick in place when the user scrolls down past a set amount of pixels. My header is 121 pixels high, but the part of the header I want to stick is the bottom 42 pixels of the header; which does work, but at the point it begins to stick the page jumps up about 50 pixels.

My thought on what could be causing the issue is $('#header').css({position: 'fixed'});. I think once fixed is applied the content, the content div no longer takes the margin into account. I've tried to play around with the different positions, but nothing has worked out for me.

I created a JSFIDDLE to better illustrate my issue.

JQUERY CODE

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

CSS CODE

body {
    margin: 0;
    padding: 0;
}
#header {
    width: 100%;
    height: 121px;
    background: url(http://libertyeaglearms.com/dev/admin/graphics/header-bg.png);
}
#content {
    margin: 10px auto;
    width: 300px;
    min-height: 600px;
}

HTML

<div id="header">header</div>
<div id="content">content goes here</div>
like image 389
Mike Avatar asked Jul 24 '13 18:07

Mike


1 Answers

Here is the problem:

When the header has a "static" positioning, it pushes the content down so it does not overlap with it. When the positioning changes from "static" to "fixed", it no longer cares whether it overlaps with the content so the content "jumps up" to the top of the page because it thinks there is nothing in it's way.

There are multiple fixes to this problem:

The easiest one is probably to add another element that essentially takes up the space that the header did when the positioning changes.

I did this by changing the display of the element to "block" when the header is "fixed" and "none" when the header is "static"

Here is an updated JSFiddle: http://jsfiddle.net/6kPzW/2/

HTML Code:

<div id="header">header</div>
<div id="header_placeholder"></div>
<div id="content">Content</div>

CSS Code:

body {
    margin: 0;
    padding: 0;
}
#header {
    width: 100%;
    height: 121px;
    background: url(http://libertyeaglearms.com/dev/admin/graphics/header-bg.png);
}
#content {
    margin: 10px auto;
    width: 300px;
    min-height: 600px;
}
#header_placeholder {
    height:121px;
    width:100%;
    display:none;
}

JQuery Code:

$(window).scroll(function()
{
    if( $(window).scrollTop() > 79 )
{
        $('#header').css({position: 'fixed'});
        $('#header_placeholder').css({display: 'block'});
} 
else 
{
        $('#header').css({position: 'static', top: '-79px'});
        $('#header_placeholder').css({display: 'none'});
}
});
like image 93
Harrison Avatar answered Oct 19 '22 21:10

Harrison