0

Is it possible to make Bootstrap only collapse the nav bar when the user is X pixels down the page?

I know this can be done for Affixing the menu by using the data attribute data-offset-top. But using this same attribute on the collapse button or on the nav div doesn't achieve this.

<nav class="navbar">
    <div class="container-fluid">
        <div>
            <a class="navbar-brand" href="/"><img src="img/logo.png" alt=""/></a>
        </div>
        <!-- Affix Navbar when 280px from top: This works -->
        <div class="navbar-header pull-right" data-spy="affix" data-offset-top="280">
            <!-- Collapse Navbar when 280px from top: Doesn't work -->
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-offset-top="280" data-target="#navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
            </button>
            <!-- The below should collapse only when the user is 280px or more from the top -->
            <div class="collapse navbar-collapse" id="navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li class="active">
                        <a class="text-uppercase page-scroll" href="#call-to-action">home</a>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</nav>
sazr
  • 24,984
  • 66
  • 194
  • 362

1 Answers1

0

You could always do it yourself with jquery.

$(window).on('scroll', function() {
    var y_scroll_pos = window.pageYOffset;
    var scroll_pos_test = 150;             // set to whatever you want it to be

    if(y_scroll_pos >= scroll_pos_test) {
       $('#navbar-collapse').collapse('hide');
    } else {
       $('#navbar-collapse').collapse('show');
    }
});

Note: Builds on this answer

If you are using lodash/underscore, you could use throttle to make sure the function doesn't execute too often.

Community
  • 1
  • 1
Kevin Wheeler
  • 1,331
  • 2
  • 15
  • 24