Javascript scroll to element with animation onclick

chilledMonkeyBrain picture chilledMonkeyBrain · Dec 18, 2014 · Viewed 9.6k times · Source

I'm just starting out with JS and struggling. I got this lovely bit of code from Adam Khoury and it's working beautifully animated scrolling down the page to the target element.

The ul is within a fixed position navigation bar.

My question is: what code would be needed to make the animation scroll both up and down when the anchor in the nav is clicked?

Answer

Dave picture Dave · Dec 18, 2014

If you're willing to use jQuery this will be much simpler. All you have to do is get the .offset() top of the element you want to scroll to and then animate the scrollTop position using jQuery .animate() function.

function autoScrollTo(el) {
    var top = $("#" + el).offset().top;
    $("html, body").animate({ scrollTop: top }, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="main-nav">
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('about');">
      About</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('testimonials');">
      Testimonials</a>
  </li>
  <li><a href="#" onclick="return false;" onmousedown="autoScrollTo('contact');">
      Contact</a>
  </li>
</ul>

<hr style="margin: 25em 0;" />

<div id="about" class="navButton">
  <p>About lorem ipsom....</p>
</div>

<div id="testimonials" class="navButton">
  <p>Testimonial lorem ipsom....</p>
</div>

<div id="contact" class="navButton">
  <p>Contact lorem ipsum</p>
</div>