2

Here's the pen...

http://codepen.io/jareko999/pen/bZXbWP

The 'if' portion of the jQuery works and adds the .fixed class to the #header when it's equal to or below 0, but it doesn't remove it when the headerTop is above 0, the 'else'. I can't figure out what's going on here. JS newb here, I'd like to understand how to get this to work. Thanks.

HTML

<div class="content">
  <div id="header"></div>
</div>

CSS

body {
    overflow-x: hidden;
    margin: 0;
}

#header {
    width: 100%;
    height: 80px;
    background: blue;
    z-index: 1;
}

.content {
    position: absolute;
    top: calc(100% - 80px);
    width: 100%;
    height: 200vh;
    background: linear-gradient(to bottom, red, yellow);
}

.fixed {
    position: fixed;
    top: 0;
    width: 100%;
    background: blue;
}

jQuery

$(window).scroll(function() {
    var top = $('#header').offset().top;
    var headerTop = (top - $(window).scrollTop());

    if (headerTop <= 0) {
        $('#header').addClass('fixed');
    } else {
        $('#header').removeClass('fixed');
    }

});
Jarek Ostrowski
  • 139
  • 1
  • 10
  • So when you set the position to fixed, what do you think happens when you check top? `console.log(top);` will show you why it does not work. – epascarello Aug 29 '16 at 15:39
  • Oh ya, duh. It would be headerTop, but I know what you meant. Hmm...I'm trying to, when the container hits a top of 0 or less, add the class fixed to the header. But when it's at 0 or above, it doesn't have it, or removes it. I'll go back to the drawing board and see what I can do. – Jarek Ostrowski Aug 29 '16 at 15:47
  • hint: height of the element. Also you can get rid of the if else and have jQuery do it. `$('#header').toggleClass('fixed', headerTop <= 0);` – epascarello Aug 29 '16 at 15:48
  • Oh man, I was writing another comment telling you I was stuck, but I got it. So instead of getting the header offset top, I got the content offset top. I wanted to get the position of the parent container instead of the header itself because the position of the container is always changing and I'm not setting it to anything. Thanks for the help! http://codepen.io/jareko999/pen/bZXbWP – Jarek Ostrowski Aug 29 '16 at 16:06

1 Answers1

2

I needed to get the parent divs offset().top instead of the actual header itself. Here's the final scroll function for a sticky header based on a parent elements top position.

http://codepen.io/jareko999/pen/bZXbWP

$(window).scroll(function() {
    var top = $('.content').offset().top;
    var headerTop = (top - $(window).scrollTop());

    $('#header').toggleClass('fixed', headerTop <= 0);
    console.log(headerTop);
});
Jarek Ostrowski
  • 139
  • 1
  • 10