Search code examples
javascriptcssscrollmenufixed

Fixed div scroll stop after


I am working on a menu, that is fixed to the right side of the page. I am using some JavaScript that keeps the menu in it's fixed position until the site reaches a specific spot (243px from the top - which clears my header). All of this is working as I intended...but I'm looking for a way for the menu to stop scrolling at a specific number of pixels from the bottom (To clear my footer - 600px).

The JavaScript looks like:

$(window).scroll(function(){
    $("#side").css("top",Math.max(15,243-$(this).scrollTop()));
});

The HTML looks like:

<div class="menu">
    <div id="side">
        <ul>
            <li>Item1</li>
            <li>Item2</li>
            <li>Item3</li>
        </ul>
    </div>
</div>

The CSS looks like:

.menu {
    right: 0;
    position: absolute;
    top: 243px;
    width: 250px;
    z-index: 5;
}

#side {
    background: #ace;
    position:fixed;
    width: 250px;
}

JS Fiddle: https://jsfiddle.net/050dqcea/
Original solution (scrolling from top): Stopping fixed position scrolling at a certain point?


Solution

  • I think I understand now, the fiddle didn't have jQuery loaded so it just wasn't running as intended.

    You can change how you want this to show or hide, that's up to you. I'd make a bit of a comment about how irritated your users might be that the menu disappears but that is up to you to decide. Alternatively you can use these triggers to "refix" your menu. The world is your oyster, etc.

    I've used $("#side").offset().top here. The idea is to check when the menu's bottom has scrolled to the top of the footer. Then to bring it back we check if the vertical scroll is less than the offset of the top of the footer.

    A fiddle for you: https://jsfiddle.net/5p90s06n/1/