jQuery smooth scrolling anchor navigation

user3574766 picture user3574766 · Aug 5, 2015 · Viewed 21.4k times · Source

I have a list based navigation at the top of my site, it's a one page site so the a hrefs are anchors to sections on the page. I've used this code: jQuery smooth scroll positioning doesn't work

Navigation:

<nav>
   <ul class="navigation">
      <li class="navigation"><a class="scroll" href="#about-me">about me</a>
      </li>
      <li class="navigation"><a class="scroll" href="#my-skills" >my skills</a>
      </li>
      <li class="navigation"><a class="scroll" href="#portfolio">portfolio</a>
      </li>
      <li class="navigation"><a class="scroll" href="#contact">contact</a>
      </li>    
   </ul>
</nav>

Section/div:

<section id="contact"> <!---->
    <div class="panel" id="contact">
        <h2>Contact</h2>
    </div>
</section> <!---->

Javascript used:

<script type="text/javascript">
$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        $target = $(target);

        $('html, body').stop().animate({
            'scrollTop':  parseInt($target.offset().top,10);
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});
</script>

The anchor works and it jumps to the section, but with no scrolling?

Answer

Guruprasad J Rao picture Guruprasad J Rao · Aug 5, 2015

There are few problems in your code:

  • You haven't closed your lis properly
  • You have same ids for section and div which is invalid
<section id="contact"> <!---->
    <div class="panel" id="contact">

So correcting the above mistakes I would like to add one more change in your JS which is:

  • No need to add parseInt to scrollTop. You can directly go with the offset().top

DEMO

$(document).ready(function(){
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();
        var target = this.hash;
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop':  $target.offset().top //no need of parseInt here
        }, 900, 'swing', function () {
            window.location.hash = target;
        });
    });
});