Janatan
Janatan

Reputation: 71

Fixed header while scroll positioning

I have an issue in where I have a fixed header whilst scrolling, but when you scroll down, the header is not fixed as another areas position is absolute.

My HTML:

<div class="titleBar">
 <div class="container">
 <h1 class="titleBar-title">Title 1</h1>
 <p class="titleBar-subTitle">Title 2</p>
</div>

<div id="subnav">
 <div class="subnav-inner">
   <ul class="subnav-list nav">
     <li><a href="#salt">Salt</a></li>
     <li><a href="#pepper">Pepper</a></li>
   </ul>
 </div>
</div>
</div>

My CSS:

.subnav-fixed {
position: fixed;
bottom: auto;
top: 0;
padding-top: 10px;
z-index: 99;
-webkit-box-shadow: 0 0 40px 0 rgba(0,0,0,0.15);
box-shadow: 0 0 40px 0 rgba(0,0,0,0.15);
}

#subnav {
width:100%;
height:40px;
background:#FFF;
position: absolute;
bottom:0;
left:0;
z-index:99;
}

Here is my JavaScript:

var myHeader = $('#subnav');
myHeader.data( 'position', myHeader.position() );
$(window).scroll(function(){
    var hPos = myHeader.data('position'), scroll = getScroll();
    if ( hPos.top < scroll.top ){
        myHeader.addClass('subnav-fixed');
    }
    else {
        myHeader.removeClass('subnav-fixed');
    }
});

function getScroll () {
    var b = document.body;
    var e = document.documentElement;
    return {
        left: parseFloat( window.pageXOffset || b.scrollLeft || e.scrollLeft ),
        top: parseFloat( window.pageYOffset || b.scrollTop || e.scrollTop )
    };
}

Which was taken from this post Fixed header while scroll

I want to keep the 'subnav' position:absolute How can I do this? I feel the JavaScript needs to be altered but I'm unsure what to enter.

Upvotes: 0

Views: 2218

Answers (2)

apaul
apaul

Reputation: 16180

This is how I've done it on my site, jsFiddle

$(window).scroll(function () {
    $('#sticky').toggleClass('scrolling', $(window).scrollTop() > $('#stickyX').offset().top);

});


 .scrolling {
    position: fixed;
    top: 0px;
    width: 98%;
    max-width: 940px;
    z-index:99999999999;
    transition:all 1s;
}

Upvotes: 2

rodneyrehm
rodneyrehm

Reputation: 13557

Have a look at position: sticky; for a CSS-only solution (webkit only, atm.) and the necessary JS fallback.

Upvotes: 0

Related Questions