Cody Cody - 1 month ago 8
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">
<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>
<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 class="nav navbar-nav navbar-right">
<li><a href="" class="entypo-linkedin" target="_blank" title="Linkedin"></a></li>
<li><a href="" class="entypo-github" target="_blank" title="Github"></a></li>
<li><a href="" class="fontawesome-fire" target="_blank" title="Free Code Camp"></a></li>
<li><a href="" class="fontawesome-sitemap" target="_blank" title="Hacker Rank"></a></li>
<li><a href="" class="zocial-html5" target="_blank" title="Codecademy"></a></li>

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?


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) {

Documentation here: