Search code examples
javascriptjqueryhtmlcssheader

Make div stick to top of page after scrolling past another div?


<div id="header"></div>
<div id="sticky"></div>
<div id="section"></div>
<div id="footer"></div>

<style>
  body { margin: 0px; background-color: #e3e3e3; }
  #header { background-color: #cb5454; height: 140px; }
  #sticky { background-color: #546bcb; height: 70px; }
  #section { height: 1500px; }
  #footer { background-color: #cb5454; height: 140px; }
</style>

Here is my code: http://jsfiddle.net/uaqh018d/

I want #sticky to stick to the top of the page after scrolling past #header. I also want it hidden until stuck. And then of course have it unstick+hide again after scrolling back up to #header.

How can I achieve this?


Solution

  • I would recommend adding a class to #sticky when it's ready to be fixed to the top of the screen, and then removing that class when you want to 'unstick' it. Then you can manipulate that class in CSS.

    e.g. for a class fixed you'd put the following in your CSS:

    #sticky {
        display: none;
        background-color: #546bcb;
        height: 70px;
    }
    #sticky.fixed {
        display: block;
        position: fixed;
        top: 0;
        width: 100%;
    }
    

    And then your jQuery would look like this:

    $(window).scroll(function() {
        var distanceFromTop = $(this).scrollTop();
        if (distanceFromTop >= $('#header').height()) {
            $('#sticky').addClass('fixed');
        } else {
            $('#sticky').removeClass('fixed');
        }
    });
    

    Here's an updated FIDDLE

    I might also recommend some jQuery fade or slide effects (see the fiddle).