Search code examples
javascripthtmlcsstwitter-bootstrapscrollspy

Bootstrap 3 scrollspy not working, codepen


This is my first post here so please don't be mad at me if I'm doing something wrong.

Here is the case: Trying to add bootstrap 3 scrollspy functionality into my code on codepen and it's basically not working. Tried different solutions from stackoverflow, etc. and nothing helps.

Is there any good person who can take look into my code?

HTML:

            <div class="container-fluid">
            <nav class="navbar navbar-default navbar-fixed-top">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">Patryk Jamróz</a>
            </div>
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
              <ul class="nav navbar-nav navbar-right">
                <li class="active"><a href="#about">About <span class="sr-only">(current)</span></a></li>
                <li><a href="#projects">Projects</a></li>
                <li><a href="#contact">Contact </a></li>
              </ul>    
          </nav><!-- navbar -->    
            <div data-spy="scroll" data-target="#nav" data-offset="0">        
            <h3 class="text-center" id="about">about</h3>
    <h3 class="text-center" id="projects">projects</h3>
    <h3 class="text-center" id="contact">contact</h3>
</div>

CSS:

.container-fluid {
    padding-right: 15px;
    padding-left: 15px;
    margin-right: auto;
    margin-left: auto;
}

.row {
  margin-left: 0;
  margin-right: 0;
}

body {
  position: relative;
}

In codepen settings tab I included:

CSS: bootstrap.min.css

JS: jquery.min.js bootstrap.min.js

Here is a link to my codepen: https://codepen.io/PatrykJamroz/full/RMZJva


Solution

  • First thing is you need to initiate the body and not a div tag so your body should have the following:

    <body data-spy="scroll" data-target=".navbar" data-offset="0">
    

    And not the:

    <div data-spy="scroll" data-target="#nav" data-offset="0">
    

    because the body is the thing that the scroll event is attached to so initiating a div does no good unless you are scrolling with that div.

    Next you need to attach it the the .navbar or the nav itself would be the best practice. And also I see that you are using jquery 3 and this may cause an issue with bootstrap 3 so you may want to switch to jquery 2.