Cody Cody - 4 months ago 26
HTML Question

Bootstrap navbar stick to top on scroll

I'm trying to have my navigation bar stick to the top of the screen on scroll. I'm using the affix plug-in to accomplish this:

<nav class="navbar navbar-default" data-spy="affix" data-offset-top="197">


Here's the relevant html.

<div class="jumbotron text-center">
<h1>Resume</h1>
</div>
<nav class="navbar navbar-default" data-spy="affix" data-offset-top="197">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse-1">
<ul class="nav navbar-nav navbar-left">
<li><a href="./index" title="Bio">Bio</a></li>
<li><a href="./Resume" title="My Resume">Resume</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="https://www.linkedin.com/in/cody-reandeau-831038115" class="entypo-linkedin" target="_blank" title="Linkedin"></a></li>
<li><a href="https://github.com/codyreandeau" class="entypo-github" target="_blank" title="Github"></a></li>
<li><a href="https://www.freecodecamp.com/codyreandeau" class="fontawesome-fire" target="_blank" title="Free Code Camp"></a></li>
<li><a href="https://www.hackerrank.com/codyareandeau" class="fontawesome-sitemap" target="_blank" title="Hacker Rank"></a></li>
<li><a href="https://www.codecademy.com/scriptSurfer86103" class="zocial-html5" target="_blank" title="Codecademy"></a></li>
</ul>
</div>
</div>
</nav>


It looks like this before the scroll:

enter image description here

Then when I scroll I'm off in the weeds:

enter image description here

I've also attempted combing it with the scrollspy and the affix plug in

<body data-spy="scroll" data-target=".navbar" data-offset="197">
<nav class="navbar navbar-default" data-spy="affix" data-offset-top="197">


And got the same results. Can anyone tell me what I'm doing wrong here?

Answer

Just add a class to the navbar on scroll:

<nav class="navbar navbar-default navbar-fixed-top">

So you just add the class navbar-fixed-top and it will stay right where you want it.

You can do that in jQuery very simply by running:

if (//scroll position reached) {
  $('nav').addClass(navbar-fixed-top)
}

Documentation here: https://getbootstrap.com/components/#navbar-fixed-top