Sticky header after some scrolling?

x0x picture x0x · Jul 3, 2014 · Viewed 30.7k times · Source

okay here's an example of what i am trying to ask, the nav bar of usatoday.

I'm using bootstrap affix. here's my code

<div class="header">
  <div class="header-1">
    <h1>this is some logo</h1>
  </div>
  <div class="header-2">
    <h3>this is some heading</h3>
  </div>
</div>
<div class="content" style="height:2500px;">
</div>
<div class="footer">
    this is a footer
</div>

JavaScript

$('.header-2').affix({
});

how can I make the div header-2 to be fixed on the top, (when there is some scrolling and the div header-2 just reach the top position) as of the site I've mentioned earlier?

I would love to see the header-1 and header-2, but some scrolling should hide header-1 and stick header-2 to the top most.

thanks

Answer

John picture John · Jul 3, 2014

See this Jsfiddle

you can check the position of the slider and add class accordingly

$(window).scroll(function () {
    if( $(window).scrollTop() > $('#header-2').offset().top && !($('#header-2').hasClass('posi'))){
      $('#header-2').addClass('posi');
    } else if ($(window).scrollTop() == 0){
      $('#header-2').removeClass('posi');
    }
});