Adding ScrollSpy to the navbar

Let's configure our top navbar to indicate our location on the page. We'll add Bootstrap's ScrollSpy behavior to the navbar:

Note

Refer to Bootstrap's ScrollSpy plugin documentation at http://getbootstrap.com/javascript/#scrollspy.

  1. Open index.html in your editor.
  2. Add these ScrollSpy attributes to the body tag:
    <body data-spy="scroll" data-target=".navbar">

    Note

    If you include more than one navbar in a page, you will need to be more specific with the data-target attribute—probably giving your ScrollSpy navbar an ID such as id="navbar-primary" and using that for the data-target value instead.

  3. With these new attributes in place, save the file, refresh your browser, and scroll up and down the page. You should see your main navigation respond as it should, indicating your position on the page as shown in the following screenshot:
    Adding ScrollSpy to the navbar

Animating the scroll

Now, let's animate the page scrolls that will be triggered by clicking on the navbar page anchors. This requires adding a few lines to our main.js file:

  1. Open js/main.js.
  2. Add the following lines within $(document).ready(function() {:
    $('#nav-main [href^=#]').click(function (e) {
      e.preventDefault();
      var div = $(this).attr('href'),
      $("html, body").animate({
        scrollTop: $(div).position().top
      }, "slow");
    });
  3. Save the file and refresh your browser.

What have we done here? We have done the following using the power of jQuery:

  • Selected the links in our .navbar element that use page anchors as their targets
  • Prevented the default click behavior
  • Animated the scrolling behavior, setting its duration to slow

Click on one of the nav items and you should see it animate the scroll!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset