Search code examples
jquerycsstwitter-bootstrapsmooth-scrolling

How can i use smooth scrolling in bootstrap an still have a link outside my page in the navbar


I have made a simple company one-page website, using a tutorial from w3School: http://www.w3schools.com/bootstrap/bootstrap_theme_company.asp

Everything works fine, until I try to add a link outside the page in my navbar:`

<!-- NAVBAR -->
    <nav class="navbar navbar-default navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span> 
      </button>
    </div>
    <div class="collapse navbar-collapse" id="myNavbar">
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#about">ABOUT</a></li>
        <li><a href="#services">SERVICES</a></li>
        <li><a href="#portfolio">PORTFOLIO</a></li>
        <li><a href="#contact">CONTACT</a></li>
        <li><a href="http://www.twitter.com/mytwitter">@mytwitter</a></li>
      </ul>
    </div>
  </div>
</nav>`

The twitter link won't open, but works if i remove the smooth scrolling script:

<script>
$(document).ready(function(){
  // Add smooth scrolling to all links in navbar + footer link
  $(".navbar a, footer a[href='#myPage']").on('click', function(event) {

  // Prevent default anchor click behavior
  event.preventDefault();

  // Store hash
  var hash = this.hash;

  // Using jQuery's animate() method to add smooth page scroll
  // The optional number (900) specifies the number of milliseconds it takes to scroll to the specified area
  $('html, body').animate({
    scrollTop: $(hash).offset().top
  }, 900, function(){

    // Add hash (#) to URL when done scrolling (default click behavior)
    window.location.hash = hash;
    });
  });
})
</script>

Is there a way to fix this?


Solution

  • Try to apply a specific class to the "smooth scrolling" elements

        <li><a class="scroll" href="#about">ABOUT</a></li>
    

    same thing to your footer link

    And then

    $(".scroll").on('click', function(event) {